<x-app-layout>
    <div class="portal-container service-page-wrap">
        @if (session('status'))
            <div class="alert alert-success">{{ session('status') }}</div>
        @endif

        @if ($errors->any())
            <div class="alert alert-error">{{ $errors->first() }}</div>
        @endif

        @php
            $payload = is_array($domain->whmcs_payload) ? $domain->whmcs_payload : [];
            $value = fn (...$keys) => collect($keys)
                ->map(fn ($key) => data_get($payload, $key))
                ->first(fn ($item) => $item !== null && trim((string) $item) !== '');

            $formatDate = function ($date) {
                if (! $date || in_array((string) $date, ['0000-00-00', '0000-00-00 00:00:00', '-'], true)) {
                    return '-';
                }

                try {
                    return \Illuminate\Support\Carbon::parse($date)->format('l, F jS, Y');
                } catch (\Throwable) {
                    return (string) $date;
                }
            };

            $formatMoney = function ($amount) use ($domain) {
                $currency = strtoupper((string) ($domain->currency ?: 'USD'));
                $formatted = number_format((float) $amount, 2);
                return $currency === 'USD' ? '$'.$formatted.' USD' : $currency.' '.$formatted;
            };

            $status = strtolower(str_replace(' ', '_', (string) $domain->status));
            $statusLabel = ucwords(str_replace('_', ' ', $status ?: 'pending'));
            $isActive = $status === 'active';
            $registrationDate = $value('regdate', 'registrationdate', 'registration_date');
            $nextDueDate = $value('nextduedate', 'next_due_date') ?: $domain->expiry_date;
            $expiryDate = $value('expirydate', 'expiry_date') ?: $domain->expiry_date;
            $firstPaymentAmount = $value('firstpaymentamount', 'first_payment_amount') ?? 0;
            $recurringAmount = $value('recurringamount', 'recurring_amount') ?? $domain->amount;
            $paymentMethod = $value('paymentmethodname', 'payment_method_name');
            $paymentMethod = $paymentMethod ?: \Illuminate\Support\Str::headline((string) ($value('paymentmethod', 'payment_method') ?: '-'));
            $registrar = $value('registrar') ?: '-';
            $registrationPeriod = (int) ($domain->registration_period ?: $value('regperiod', 'registrationperiod') ?: 0);
            $doNotRenew = filter_var($value('donotrenew', 'do_not_renew') ?? false, FILTER_VALIDATE_BOOLEAN);
            $autoRenewLabel = $doNotRenew ? 'Disabled' : 'Enabled';
            $lastUpdated = optional($domain->whmcs_synced_at)->format('d M Y h:i A') ?: '-';

            $sslStatus = $value('sslstatus', 'ssl_status', 'ssl.status');
            $sslIssuer = $value('sslissuer', 'ssl_issuer', 'ssl.issuer');
            $sslStartDate = $value('sslstartdate', 'ssl_start_date', 'ssl.start_date');
            $sslExpiryDate = $value('sslexpirydate', 'ssl_expiry_date', 'ssl.expiry_date');
            $hasSslData = $sslStatus || $sslIssuer || $sslStartDate || $sslExpiryDate;

            $nameserverValues = array_pad(array_values($nameservers ?? []), 5, '');
        @endphp

        <div class="service-topbar">
            <a class="service-back-link" href="{{ route('client.domains') }}">← Back to Domains</a>
        </div>

        <section class="service-hero-card">
            <div class="service-hero-main">
                <span class="service-eyebrow">Domain Registration</span>
                <h1>{{ $domain->domain_name }}</h1>
                <p>Manage domain information and registrar settings from your client portal.</p>
            </div>
            <div class="service-hero-status">
                <span class="status-pill {{ $status }}">{{ $statusLabel }}</span>
                <small>Expires: {{ $formatDate($expiryDate) }}</small>
            </div>
        </section>

        <div class="service-dashboard-grid">
            <main class="service-dashboard-main">
                <section class="service-panel">
                    <div class="service-panel-head inline">
                        <div>
                            <span class="service-eyebrow">Overview</span>
                            <h2>Domain Details</h2>
                        </div>
                        <small>Last Updated: {{ $lastUpdated }}</small>
                    </div>

                    <div class="domain-overview-grid">
                        <div class="domain-overview-item">
                            <span>Domain</span>
                            <strong>{{ $domain->domain_name }}</strong>
                        </div>
                        <div class="domain-overview-item">
                            <span>First Payment Amount</span>
                            <strong>{{ $formatMoney($firstPaymentAmount) }}</strong>
                        </div>
                        <div class="domain-overview-item">
                            <span>Registration Date</span>
                            <strong>{{ $formatDate($registrationDate) }}</strong>
                        </div>
                        <div class="domain-overview-item">
                            <span>Recurring Amount</span>
                            <strong>{{ $formatMoney($recurringAmount) }}{{ $registrationPeriod > 0 ? ' Every '.$registrationPeriod.' Year/s' : '' }}</strong>
                        </div>
                        <div class="domain-overview-item">
                            <span>Next Due Date</span>
                            <strong>{{ $formatDate($nextDueDate) }}</strong>
                        </div>
                        <div class="domain-overview-item">
                            <span>Payment Method</span>
                            <strong>{{ $paymentMethod }}</strong>
                        </div>
                    </div>
                </section>

                <section class="service-panel service-actions-panel">
                    <div class="service-panel-head">
                        <div>
                            <span class="service-eyebrow">Quick Actions</span>
                            <h2>Manage Domain</h2>
                        </div>
                        <p>Nameserver changes are submitted directly to WHMCS and the configured registrar.</p>
                    </div>

                    <div class="service-actions-grid">
                        <a class="service-action-card primary" href="#nameservers">
                            <span class="service-action-icon">DNS</span>
                            <strong>Change Nameservers</strong>
                            <small>Update where this domain points</small>
                        </a>

                        <a class="service-action-card" href="#renew-domain">
                            <span class="service-action-icon">↻</span>
                            <strong>Renew Domain</strong>
                            <small>Create and pay the renewal invoice here</small>
                        </a>
                    </div>
                </section>

                <section class="service-panel" id="renew-domain">
                    <div class="service-panel-head">
                        <div>
                            <span class="service-eyebrow">Renewal</span>
                            <h2>Renew Your Domain</h2>
                        </div>
                        <p>The renewal invoice and payment stay inside this portal. The registrar renewal is submitted after WHMCS confirms the invoice as paid.</p>
                    </div>

                    @if ($pendingRenewalInvoice)
                        <div class="domain-renewal-pending">
                            <div>
                                <strong>Renewal invoice already created</strong>
                                <span>Invoice {{ $pendingRenewalInvoice->invoice_number }} is waiting for payment.</span>
                            </div>
                            <a class="primary-btn" href="{{ route('client.invoices.show', $pendingRenewalInvoice) }}">View & Pay Invoice</a>
                        </div>
                    @elseif (in_array($status, ['active', 'expired'], true) && count($renewalOptions ?? []) > 0)
                        <form method="POST" action="{{ route('client.domains.renew.submit', $domain) }}" class="domain-renewal-form">
                            @csrf
                            <label>
                                <span>Renewal Period</span>
                                <select name="years" required>
                                    @foreach ($renewalOptions as $years => $option)
                                        <option value="{{ $years }}" @selected((int) old('years', $registrationPeriod ?: array_key_first($renewalOptions)) === (int) $years)>
                                            {{ $years }} {{ (int) $years === 1 ? 'Year' : 'Years' }} — {{ $formatMoney(data_get($option, 'unit_price', 0)) }}
                                        </option>
                                    @endforeach
                                </select>
                            </label>

                            <div class="domain-renewal-submit">
                                <div>
                                    <strong>Next step: payment</strong>
                                    <small>A WHMCS renewal invoice will be created and opened on the portal invoice page.</small>
                                </div>
                                <button class="service-submit-btn" type="submit">Create Renewal Invoice</button>
                            </div>
                        </form>
                    @else
                        <div class="domain-inline-notice">
                            {{ $renewalNotice ?: 'This domain cannot be renewed in its current status.' }}
                        </div>
                    @endif
                </section>

                @if ($isActive)
                    <section class="service-panel" id="nameservers">
                        <div class="service-panel-head">
                            <div>
                                <span class="service-eyebrow">DNS Routing</span>
                                <h2>Nameservers</h2>
                            </div>
                            <p>At least two nameservers are required. DNS propagation may take several hours after an update.</p>
                        </div>

                        @if ($nameserverNotice)
                            <div class="domain-inline-notice">{{ $nameserverNotice }}</div>
                        @endif

                        <form method="POST" action="{{ route('client.domains.nameservers.update', $domain) }}" class="domain-nameserver-form">
                            @csrf
                            @foreach (range(1, 5) as $number)
                                <label>
                                    <span>Nameserver {{ $number }}{{ $number <= 2 ? ' *' : '' }}</span>
                                    <input
                                        type="text"
                                        name="ns{{ $number }}"
                                        value="{{ old('ns'.$number, $nameserverValues[$number - 1]) }}"
                                        placeholder="ns{{ $number }}.example.com"
                                        {{ $number <= 2 ? 'required' : '' }}
                                        autocomplete="off"
                                    >
                                </label>
                            @endforeach

                            <div class="domain-form-actions">
                                <button class="service-submit-btn" type="submit">Save Nameservers</button>
                            </div>
                        </form>
                    </section>
                @else
                    <section class="service-panel domain-unavailable-panel">
                        <span class="service-eyebrow">Management Unavailable</span>
                        <h2>Nameserver controls are not available yet</h2>
                        <p>This domain is currently {{ strtolower($statusLabel) }}. Registrar controls will become available after activation.</p>
                    </section>
                @endif

                @if ($hasSslData)
                    <section class="service-panel">
                        <div class="service-panel-head">
                            <div>
                                <span class="service-eyebrow">Security</span>
                                <h2>SSL Status</h2>
                            </div>
                        </div>
                        <div class="domain-overview-grid">
                            <div class="domain-overview-item"><span>Status</span><strong>{{ $sslStatus ?: '-' }}</strong></div>
                            <div class="domain-overview-item"><span>Issuer</span><strong>{{ $sslIssuer ?: '-' }}</strong></div>
                            <div class="domain-overview-item"><span>Start Date</span><strong>{{ $formatDate($sslStartDate) }}</strong></div>
                            <div class="domain-overview-item"><span>Expiry Date</span><strong>{{ $formatDate($sslExpiryDate) }}</strong></div>
                        </div>
                    </section>
                @endif
            </main>

            <aside class="service-dashboard-side">
                <section class="service-panel service-summary-panel">
                    <span class="service-eyebrow">Summary</span>
                    <h2>Domain Summary</h2>
                    <dl class="service-summary-list refined">
                        <div><dt>Status</dt><dd><span class="status-pill {{ $status }}">{{ $statusLabel }}</span></dd></div>
                        <div><dt>Registration Period</dt><dd>{{ $registrationPeriod > 0 ? $registrationPeriod.' year(s)' : '-' }}</dd></div>
                        <div><dt>Expiry Date</dt><dd>{{ $formatDate($expiryDate) }}</dd></div>
                        <div><dt>Auto Renewal</dt><dd>{{ $autoRenewLabel }}</dd></div>
                        <div><dt>Registrar</dt><dd>{{ $registrar }}</dd></div>
                    </dl>
                </section>
            </aside>
        </div>
    </div>
</x-app-layout>
