<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
            $displayMoney = function ($service) {
                $amount = number_format((float) $service->amount, 2);
                return strtoupper((string) $service->currency) === 'USD'
                    ? '$'.$amount.' USD'
                    : strtoupper((string) $service->currency).' '.$amount;
            };

            $status = strtolower(str_replace(' ', '_', (string) $service->status));
            $statusLabel = ucwords(str_replace('_', ' ', $status ?: 'pending'));
            $isActive = $status === 'active';
            $payload = is_array($service->whmcs_payload) ? $service->whmcs_payload : [];
            $stat = fn (...$keys) => collect($keys)->map(fn ($key) => data_get($payload, $key))->first(fn ($value) => $value !== null && $value !== '');
            $diskUsed = $stat('diskusage', 'disk_usage', 'service.diskusage', 'usage.diskusage') ?? 0;
            $diskLimit = $stat('disklimit', 'disk_limit', 'service.disklimit', 'usage.disklimit') ?? 'Unlimited';
            $bwUsed = $stat('bwusage', 'bandwidthusage', 'bw_usage', 'service.bwusage', 'usage.bwusage') ?? 0;
            $bwLimit = $stat('bwlimit', 'bandwidthlimit', 'bw_limit', 'service.bwlimit', 'usage.bwlimit') ?? 'Unlimited';
            $lastUpdated = $stat('lastupdate', 'last_updated', 'service.lastupdate', 'usage.lastupdate') ?: optional($service->whmcs_synced_at)->format('d M Y h:i A');

            $serviceText = strtolower(trim(implode(' ', array_filter([
                $service->name,
                $service->service_type,
                data_get($payload, 'groupname'),
                data_get($payload, 'type'),
                data_get($payload, 'producttype'),
            ]))));
            $isReseller = str_contains($serviceText, 'reseller');
            $panelName = $isReseller ? 'WHM' : 'cPanel';

            $diskPercent = is_numeric($diskLimit) && (float) $diskLimit > 0 ? min(100, round(((float) $diskUsed / (float) $diskLimit) * 100)) : 0;
            $bwPercent = is_numeric($bwLimit) && (float) $bwLimit > 0 ? min(100, round(((float) $bwUsed / (float) $bwLimit) * 100)) : 0;
        @endphp

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

        <section class="service-hero-card">
            <div class="service-hero-main">
                <span class="service-eyebrow">{{ $isReseller ? 'Reseller Hosting Service' : 'Hosting Service' }}</span>
                <h1>{{ $service->name }}</h1>
                <p>{{ $service->domain_name ?: 'No domain assigned yet' }}</p>
            </div>
            <div class="service-hero-status">
                <span class="status-pill {{ $status }}">{{ $statusLabel }}</span>
                <small>Next due: {{ optional($service->next_due_date)->format('M d, Y') ?: '-' }}</small>
            </div>
        </section>

        @if ($isActive)
        <div class="service-dashboard-grid">
            <main class="service-dashboard-main">
                <section class="service-panel service-actions-panel">
                    <div class="service-panel-head">
                        <div>
                            <span class="service-eyebrow">Quick Actions</span>
                            <h2>Manage Hosting</h2>
                        </div>
                        <p>Credentials are hidden. Access is handled through secure single sign-on.</p>
                    </div>

                    <div class="service-actions-grid">
                        <a class="service-action-card primary" href="{{ route('client.services.cpanel-sso', $service) }}" target="_blank" rel="noopener noreferrer">
                            <span class="service-action-icon">↗</span>
                            <strong>Login to {{ $panelName }}</strong>
                            <small>{{ $isReseller ? 'Open WHM reseller panel' : 'Open cPanel hosting panel' }}</small>
                        </a>

                        <a class="service-action-card" href="{{ route('client.services.upgrade', $service) }}">
                            <span class="service-action-icon">⇅</span>
                            <strong>Upgrade / Downgrade</strong>
                            <small>Change package from this portal</small>
                        </a>
                    </div>
                </section>

                <section class="service-panel usage-panel">
                    <div class="service-panel-head inline">
                        <div>
                            <span class="service-eyebrow">Usage Statistics</span>
                            <h2>Resource Usage</h2>
                        </div>
                        <small>Last Updated: {{ $lastUpdated ?: '-' }}</small>
                    </div>

                    <div class="usage-stat-grid refined">
                        <div class="usage-stat-box refined">
                            <div class="usage-stat-top">
                                <span>Disk Usage</span>
                                <strong>{{ $diskUsed }} M</strong>
                            </div>
                            <div class="usage-meter"><i style="width: {{ $diskPercent }}%"></i></div>
                            <small>{{ $diskUsed }} M / {{ $diskLimit }} MB</small>
                        </div>

                        <div class="usage-stat-box refined">
                            <div class="usage-stat-top">
                                <span>Bandwidth Usage</span>
                                <strong>{{ $bwUsed }} M</strong>
                            </div>
                            <div class="usage-meter"><i style="width: {{ $bwPercent }}%"></i></div>
                            <small>{{ $bwUsed }} M / {{ $bwLimit }} M</small>
                        </div>
                    </div>
                </section>

                <section class="service-panel password-panel">
                    <div class="service-panel-head">
                        <div>
                            <span class="service-eyebrow">Security</span>
                            <h2>Change {{ $panelName }} Password</h2>
                        </div>
                        <p>Choose a strong password. You may need to sign in again after the password changes.</p>
                    </div>

                    <form method="POST" action="{{ route('client.services.change-password', $service) }}" class="change-password-inline">
                        @csrf
                        <input type="password" name="service_password" placeholder="New service password" required minlength="8" autocomplete="new-password">
                        <input type="password" name="service_password_confirmation" placeholder="Confirm new password" required minlength="8" autocomplete="new-password">
                        <button class="service-submit-btn" type="submit">Change Password</button>
                    </form>
                </section>
            </main>

            <aside class="service-dashboard-side">
                <section class="service-panel service-summary-panel">
                    <span class="service-eyebrow">Summary</span>
                    <h2>Service Summary</h2>
                    <dl class="service-summary-list refined">
                        <div><dt>Domain</dt><dd>{{ $service->domain_name ?: '-' }}</dd></div>
                        <div><dt>Billing Cycle</dt><dd>{{ $service->billing_cycle ?: '-' }}</dd></div>
                        <div><dt>Amount</dt><dd>{{ $displayMoney($service) }}</dd></div>
                        <div><dt>Next Due Date</dt><dd>{{ optional($service->next_due_date)->format('l, F jS, Y') ?: '-' }}</dd></div>
                    </dl>
                </section>
            </aside>
        </div>
        @else
            <section class="service-panel" style="margin-top:24px; text-align:center; padding:42px 24px;">
                <span class="service-eyebrow">Activation Pending</span>
                <h2 style="margin:10px 0 8px;">Management tools are not available yet</h2>
                <p style="margin:0 auto; max-width:620px; color:#64748b; line-height:1.7;">
                    This service is currently {{ strtolower($statusLabel) }}. cPanel login, password changes, and package changes will become available after activation.
                </p>
            </section>
        @endif
    </div>
</x-app-layout>
