<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pricing Plans — WhatsApp Cloud API</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; background:#f0f2f5; min-height:100vh; display:flex; flex-direction:column; }

        /* ── HEADER ── */
        header { background:#000; color:#fff; height:58px; display:flex; align-items:center; justify-content:space-between; padding:0 1.75rem; position:fixed; top:0;left:0;right:0; z-index:200; border-bottom:1px solid #1a1a1a; }
        .brand { display:flex; align-items:center; gap:.65rem; font-size:1rem; font-weight:700; color:#fff; }
        .brand svg { width:30px; height:30px; }
        .brand-logo { height:36px; width:auto; max-width:140px; object-fit:contain; flex-shrink:1; min-width:0; }
        .user-avatar { width:32px; height:32px; border-radius:50%; object-fit:cover; border:2px solid #333; flex-shrink:0; }
        .user-avatar-initials { width:32px; height:32px; border-radius:50%; background:#25d366; display:flex; align-items:center; justify-content:center; font-weight:700; font-size:.82rem; color:#000; flex-shrink:0; }
        .header-right { display:flex; align-items:center; gap:1rem; font-size:.85rem; }
        .header-right .username { color:#aaa; font-weight:500; }
        .btn-logout { background:transparent; border:1px solid #333; color:#ccc; padding:.38rem 1rem; border-radius:7px; cursor:pointer; font-size:.82rem; font-weight:600; transition:.2s; }
        .btn-logout:hover { border-color:#666; color:#fff; }

        /* ── LAYOUT ── */
        .layout { display:flex; flex:1; margin-top:58px; min-height:calc(100vh - 58px); }

        /* ── SIDEBAR ── */
        aside { width:248px; background:#000; position:fixed; top:58px; left:0; bottom:0; overflow-y:auto; padding:1.25rem 0 2rem; border-right:1px solid #1c1c1c; scrollbar-width:thin; scrollbar-color:#2a2a2a #000; }
        .nav-section-label { padding:1.2rem 1.4rem .4rem; font-size:.63rem; font-weight:700; letter-spacing:1.4px; color:#aab; text-transform:uppercase; }
        .nav-item { display:flex; align-items:center; gap:.8rem; padding:.7rem 1.4rem; color:#d1d5db; text-decoration:none; font-size:.88rem; font-weight:500; border-left:3px solid transparent; transition:.18s; white-space:nowrap; cursor:pointer; }
        .nav-item:hover { background:#25d366; color:#000; border-left-color:#1db954; }
        .nav-item:hover svg { opacity:1; color:#000; }
        .nav-item.active { background:#25d366; color:#000 !important; border-left-color:#1db954; font-weight:700; }
        .nav-item.active svg { opacity:1; color:#000; }
        .nav-item svg { width:17px; height:17px; flex-shrink:0; opacity:.7; }
        .nav-sep { height:1px; background:#1a1a1a; margin:.6rem 0; }

        /* ── MAIN ── */
        main { margin-left:248px; flex:1; padding:1.75rem 2rem; animation:fadeIn .18s ease both; }
        @keyframes fadeIn  { from{opacity:0;transform:translateY(8px)}  to{opacity:1;transform:translateY(0)} }
        @keyframes fadeOut { from{opacity:1;transform:translateY(0)} to{opacity:0;transform:translateY(-8px)} }

        .page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:1.5rem; }
        .page-header h1 { font-size:1.35rem; font-weight:800; color:#0f0f0f; }
        .page-header p  { font-size:.85rem; color:#9ca3af; margin-top:.2rem; }
        .btn-add { display:inline-flex; align-items:center; gap:.5rem; background:#0f0f0f; color:#fff; border:none; padding:.55rem 1.1rem; border-radius:9px; font-size:.85rem; font-weight:700; cursor:pointer; transition:.2s; }
        .btn-add:hover { background:#1a1a1a; }
        .btn-add svg { width:16px; height:16px; }

        /* ── PLANS GRID ── */
        .plans-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(300px, 1fr)); gap:1.25rem; }

        .plan-card { background:#fff; border-radius:16px; box-shadow:0 1px 3px rgba(0,0,0,.06),0 4px 12px rgba(0,0,0,.04); overflow:hidden; transition:box-shadow .2s, transform .2s; }
        .plan-card:hover { box-shadow:0 8px 28px rgba(0,0,0,.12); transform:translateY(-3px); }
        .plan-top-bar { height:4px; background:linear-gradient(90deg,#25d366,#075e54); }
        .plan-body { padding:1.4rem 1.5rem 1rem; }
        .plan-head { display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:.9rem; }
        .plan-name { font-size:1.05rem; font-weight:800; color:#0f0f0f; }
        .plan-desc { font-size:.8rem; color:#9ca3af; margin-top:.25rem; line-height:1.5; }
        .plan-status-toggle { cursor:pointer; }
        .pill { display:inline-block; padding:.22rem .65rem; border-radius:20px; font-size:.72rem; font-weight:700; }
        .pill-on  { background:#f0fdf4; color:#15803d; }
        .pill-off { background:#f1f5f9; color:#6b7280; }

        .plan-price { display:flex; align-items:baseline; gap:.35rem; margin:.75rem 0; }
        .price-amount { font-size:2rem; font-weight:800; color:#0f0f0f; letter-spacing:-1px; }
        .price-currency { font-size:1rem; font-weight:700; color:#6b7280; margin-bottom:4px; }
        .price-period { font-size:.8rem; color:#9ca3af; }

        .plan-limits { display:grid; grid-template-columns:1fr 1fr 1fr; gap:.5rem; margin:.85rem 0; }
        .limit-box { background:#f8fafc; border-radius:8px; padding:.55rem .6rem; text-align:center; }
        .limit-val { font-size:.95rem; font-weight:800; color:#0f0f0f; line-height:1.2; }
        .limit-val.is-unl { font-size:.65rem; color:#25d366; }
        .limit-lbl { font-size:.65rem; color:#9ca3af; margin-top:1px; }

        .plan-features { margin:.75rem 0; }
        .feat-item { display:flex; align-items:center; gap:.5rem; font-size:.8rem; color:#374151; padding:.25rem 0; }
        .feat-dot { width:6px; height:6px; border-radius:50%; background:#25d366; flex-shrink:0; }

        .plan-footer { display:flex; align-items:center; justify-content:space-between; padding:.9rem 1.5rem 1.1rem; border-top:1px solid #f8fafc; }
        .plan-meta { font-size:.74rem; color:#9ca3af; }
        .plan-actions { display:flex; gap:.45rem; }
        .act-btn { display:inline-flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:7px; border:none; cursor:pointer; transition:.18s; }
        .act-btn svg { width:14px; height:14px; }
        .act-edit { background:#f0fdf4; color:#16a34a; }
        .act-edit:hover { background:#dcfce7; }
        .act-del  { background:#fef2f2; color:#dc2626; }
        .act-del:hover { background:#fee2e2; }

        /* ── EMPTY STATE ── */
        .empty-state { background:#fff; border-radius:16px; padding:4rem 2rem; text-align:center; box-shadow:0 1px 3px rgba(0,0,0,.06); }
        .empty-state svg { width:52px; height:52px; color:#d1d5db; margin:0 auto 1rem; display:block; }
        .empty-state h3 { font-size:1rem; font-weight:700; color:#374151; margin-bottom:.4rem; }
        .empty-state p { font-size:.85rem; color:#9ca3af; }

        /* ── TABLE fallback (also show table view) ── */
        .table-section { margin-top:2rem; }
        .section-title { font-size:.72rem; font-weight:700; letter-spacing:1.1px; text-transform:uppercase; color:#9ca3af; margin-bottom:.75rem; }
        .table-wrap { background:#fff; border-radius:14px; box-shadow:0 1px 3px rgba(0,0,0,.06); overflow:hidden; }
        table { width:100%; border-collapse:collapse; }
        thead { background:#f8fafc; }
        th { padding:.75rem 1.1rem; font-size:.72rem; font-weight:700; color:#9ca3af; text-transform:uppercase; letter-spacing:.6px; text-align:left; border-bottom:1px solid #f1f5f9; white-space:nowrap; }
        td { padding:.8rem 1.1rem; font-size:.85rem; color:#374151; border-bottom:1px solid #f8fafc; vertical-align:middle; }
        tr:last-child td { border-bottom:none; }
        tr:hover td { background:#fafffe; }

        /* ── MODAL ── */
        .modal-backdrop { position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:600; display:none; align-items:flex-start; justify-content:center; padding:2rem 1rem; overflow-y:auto; }
        .modal-backdrop.open { display:flex; }

        .add-modal { background:#fff; border-radius:18px; width:100%; max-width:680px; box-shadow:0 24px 70px rgba(0,0,0,.28); animation:modalPop .18s ease both; margin:auto; }
        @keyframes modalPop { from{opacity:0;transform:scale(.96) translateY(10px)} to{opacity:1;transform:scale(1) translateY(0)} }

        .add-modal-header { display:flex; align-items:center; justify-content:space-between; padding:1.2rem 1.6rem; border-bottom:1px solid #f1f5f9; }
        .add-modal-header h3 { font-size:1.05rem; font-weight:800; color:#0f0f0f; }
        .add-modal-close { width:32px; height:32px; background:#f1f5f9; border:none; border-radius:8px; cursor:pointer; display:flex; align-items:center; justify-content:center; color:#6b7280; transition:.15s; }
        .add-modal-close:hover { background:#e2e8f0; color:#0f0f0f; }

        .add-modal-body { padding:1.5rem 1.6rem; }

        .am-section-head { font-size:.65rem; font-weight:700; letter-spacing:1.3px; text-transform:uppercase; color:#9ca3af; padding:.6rem 0 .7rem; border-bottom:1px solid #f1f5f9; margin-bottom:1rem; }
        .am-section-head:not(:first-child) { margin-top:1.5rem; }

        .am-grid { display:grid; grid-template-columns:1fr 1fr; gap:.9rem; }
        .am-group { display:flex; flex-direction:column; gap:.35rem; }
        .am-group.full { grid-column:1/-1; }
        .am-group.col3 { grid-column:span 1; }

        .am-label { font-size:.78rem; font-weight:600; color:#374151; }
        .am-label .opt { font-weight:400; color:#b0b7c3; font-size:.74rem; }
        .am-hint  { font-size:.72rem; color:#9ca3af; margin-top:-2px; }

        .am-input, .am-select, .am-textarea {
            padding:.62rem .9rem;
            border:1.5px solid #e5e7eb;
            border-radius:10px;
            font-size:.88rem;
            color:#111;
            background:#fff;
            outline:none;
            font-family:inherit;
            transition:.18s;
            width:100%;
        }
        .am-textarea { resize:vertical; min-height:72px; }
        .am-input:focus, .am-select:focus, .am-textarea:focus { border-color:#25d366; box-shadow:0 0 0 3px rgba(37,211,102,.1); }
        .am-input.err { border-color:#ef4444; }
        .am-err { font-size:.74rem; color:#ef4444; }

        /* Period toggle */
        .period-toggle { display:flex; gap:0; border:1.5px solid #e5e7eb; border-radius:10px; overflow:hidden; }
        .period-toggle label { flex:1; text-align:center; padding:.62rem .5rem; font-size:.85rem; font-weight:600; cursor:pointer; color:#6b7280; transition:.15s; user-select:none; }
        .period-toggle input[type=radio] { display:none; }
        .period-toggle input[type=radio]:checked + label { background:#0f0f0f; color:#fff; }

        /* Limit inputs row */
        .limits-row { display:grid; grid-template-columns:1fr 1fr 1fr; gap:.9rem; }

        /* Plugin chips */
        .plugin-chips { display:flex; flex-wrap:wrap; gap:.5rem; margin-top:.4rem; }
        .plugin-chip { display:flex; align-items:center; gap:.4rem; padding:.35rem .75rem; border:1.5px solid #e5e7eb; border-radius:8px; font-size:.8rem; cursor:pointer; color:#374151; transition:.15s; user-select:none; }
        .plugin-chip input { display:none; }
        .plugin-chip.selected { border-color:#25d366; background:#f0fdf4; color:#15803d; font-weight:600; }

        .add-modal-footer { display:flex; align-items:center; justify-content:flex-end; gap:.75rem; padding:1rem 1.6rem; border-top:1px solid #f1f5f9; background:#fafafa; border-radius:0 0 18px 18px; }
        .btn-cancel-modal { background:#f1f5f9; color:#374151; border:none; padding:.65rem 1.4rem; border-radius:9px; font-size:.88rem; font-weight:600; cursor:pointer; }
        .btn-save { background:#0f0f0f; color:#fff; border:none; padding:.65rem 1.5rem; border-radius:10px; font-size:.88rem; font-weight:700; cursor:pointer; transition:.18s; display:flex; align-items:center; gap:.5rem; }
        .btn-save:hover { background:#1a1a1a; }

        /* Delete modal */
        .del-modal { background:#fff; border-radius:16px; padding:2rem; max-width:400px; width:100%; box-shadow:0 20px 60px rgba(0,0,0,.25); text-align:center; margin:auto; }
        .del-modal h3 { font-size:1.1rem; font-weight:800; color:#0f0f0f; margin-bottom:.5rem; }
        .del-modal p  { font-size:.88rem; color:#6b7280; margin-bottom:1.5rem; }
        .modal-actions { display:flex; gap:.75rem; justify-content:center; }
        .btn-del-modal { background:#ef4444; color:#fff; border:none; padding:.65rem 1.4rem; border-radius:9px; font-size:.88rem; font-weight:700; cursor:pointer; }
        .btn-del-modal:hover { background:#dc2626; }
    </style>
</head>
<body>

<!-- HEADER -->
@php
    $appLogo   = \App\Models\Setting::get('app_logo', '');
    $appName   = \App\Models\Setting::get('project_name', 'On Cloud API');
    $hasLogo   = $appLogo && file_exists(public_path('uploads/' . $appLogo));
    $userPhoto = $authUser->profile_photo_path ?? '';
    $hasPhoto  = $userPhoto && file_exists(public_path('uploads/' . $userPhoto));
    $initials  = strtoupper(substr($authUser->name ?? 'U', 0, 1));
@endphp
<header>
    <div class="brand">
        @if($hasLogo)
            <img src="{{ asset('uploads/' . $appLogo) }}" class="brand-logo" alt="{{ $appName }}">
        @else
            <svg viewBox="0 0 48 48" fill="none">
                <circle cx="24" cy="24" r="24" fill="#25D366"/>
                <path d="M24 10C16.268 10 10 16.268 10 24c0 2.637.718 5.107 1.97 7.23L10 38l7-1.93A13.93 13.93 0 0024 38c7.732 0 14-6.268 14-14S31.732 10 24 10z" fill="white"/>
                <path d="M19.5 17.5c-.4-.9-1-1-1.4-1h-1.2c-.4 0-1 .15-1.5.7s-2 2-2 4.85 2.05 5.6 2.35 5.95 4 6.3 9.75 8.6c4.8 1.9 5.75 1.5 6.75 1.4s3.25-1.35 3.7-2.65.45-2.4.3-2.65-1.15-1.1-2.4-1.7-3.05-1.5-3.5-1.65-.8-.25-1.15.25-1.3 1.65-1.6 2c-.3.3-.6.35-1.1.1s-2.15-1.05-4.1-2.8c-1.52-1.5-2.53-3.35-2.83-3.85s-.03-.75.22-1l.55-.65c.2-.2.3-.45.45-.75s.05-.55-.05-.75l-1.74-3.6z" fill="#25D366"/>
            </svg>
        @endif
    </div>
    <div class="header-right">
        @if($hasPhoto)
            <img src="{{ asset('uploads/' . $userPhoto) }}" class="user-avatar" alt="{{ $authUser->name }}">
        @else
            <div class="user-avatar-initials">{{ $initials }}</div>
        @endif
        <span class="username">{{ $authUser->name }}</span>
        <form method="POST" action="{{ route('logout') }}">
            @csrf
            <button type="submit" class="btn-logout">Logout</button>
        </form>
    </div>
</header>

<div class="layout">
    <!-- SIDEBAR -->
    <aside>
        <div class="nav-section-label">Main</div>
        <a href="{{ route('dashboard') }}" class="nav-item">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>
            Dashboard
        </a>
        <div class="nav-sep"></div>
        <div class="nav-section-label">Management</div>
        <a href="#" class="nav-item">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            Subscriptions
        </a>
        <a href="{{ route('companies') }}" class="nav-item">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
            Companies
        </a>
        <a href="{{ route('pricing-plans') }}" class="nav-item active">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2M9 12h6m-6 4h6"/></svg>
            Pricing Plans
        </a>
        <div class="nav-sep"></div>
        <div class="nav-section-label">Explore</div>
        <a href="#" class="nav-item">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"/></svg>
            Today Messages
        </a>
        <a href="#" class="nav-item">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z"/></svg>
            Today Campaigns
        </a>
        <a href="{{ route('apps') }}" class="nav-item">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
            Apps
        </a>
        <div class="nav-sep"></div>
        <div class="nav-section-label">System</div>
        <a href="{{ route('settings') }}" class="nav-item">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
            Settings
        </a>
    </aside>

    <!-- MAIN -->
    <main>

        @if(session('success'))
        <div style="background:#f0fdf4;border:1px solid #bbf7d0;color:#15803d;padding:.7rem 1rem;border-radius:9px;margin-bottom:1.25rem;font-size:.85rem;font-weight:600;">
            ✓ {{ session('success') }}
        </div>
        @endif

        <div class="page-header">
            <div>
                <h1>Pricing Plans</h1>
                <p>Manage subscription plans for your clients</p>
            </div>
            <button onclick="openAddModal()" class="btn-add">
                <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
                Add Plan
            </button>
        </div>

        @if($plans->isEmpty())
        <div class="empty-state">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2M9 12h6m-6 4h6"/></svg>
            <h3>No plans yet</h3>
            <p>Click "Add Plan" to create your first pricing plan.</p>
        </div>
        @else

        <!-- CARDS GRID -->
        <div class="plans-grid">
            @foreach($plans as $plan)
            @php
                $feats = $plan->features_array;
                $planPluginKeys = $plan->plugins ? array_filter(array_map('trim', explode(',', $plan->plugins))) : [];
                $planApps = $plan->plugins
                    ? $apps->whereIn('app_key', $planPluginKeys)
                    : collect();
            @endphp
            <div class="plan-card">
                <div class="plan-top-bar"></div>
                <div class="plan-body">
                    <div class="plan-head">
                        <div>
                            <div class="plan-name">{{ $plan->name }}</div>
                            @if($plan->description)
                            <div class="plan-desc">{{ Str::limit($plan->description, 70) }}</div>
                            @endif
                        </div>
                        <form method="POST" action="{{ route('pricing-plans.toggle', $plan) }}" class="plan-status-toggle">
                            @csrf @method('PATCH')
                            <button type="submit" style="background:none;border:none;cursor:pointer;padding:0;" title="Toggle active">
                                <span class="pill {{ $plan->is_active ? 'pill-on' : 'pill-off' }}">
                                    {{ $plan->is_active ? '● Active' : '○ Inactive' }}
                                </span>
                            </button>
                        </form>
                    </div>

                    <div class="plan-price">
                        <span class="price-currency">$</span>
                        <span class="price-amount">{{ number_format($plan->price, 2) }}</span>
                        <span class="price-period">/ {{ ['1month'=>'1 Month','3months'=>'3 Months','6months'=>'6 Months','1year'=>'1 Year'][$plan->period] ?? $plan->period }}</span>
                    </div>

                    <div class="plan-limits">
                        <div class="limit-box">
                            <div class="limit-val {{ $plan->campaigns_limit == 0 ? 'is-unl' : '' }}">{{ $plan->campaigns_limit == 0 ? 'Unlimited' : $plan->campaigns_limit }}</div>
                            <div class="limit-lbl">Campaigns</div>
                        </div>
                        <div class="limit-box">
                            <div class="limit-val {{ $plan->messages_limit == 0 ? 'is-unl' : '' }}">{{ $plan->messages_limit == 0 ? 'Unlimited' : number_format($plan->messages_limit) }}</div>
                            <div class="limit-lbl">Messages</div>
                        </div>
                        <div class="limit-box">
                            <div class="limit-val {{ $plan->contacts_limit == 0 ? 'is-unl' : '' }}">{{ $plan->contacts_limit == 0 ? 'Unlimited' : number_format($plan->contacts_limit) }}</div>
                            <div class="limit-lbl">Contacts</div>
                        </div>
                    </div>

                    @if(count($feats))
                    <div class="plan-features">
                        @foreach(array_slice($feats, 0, 4) as $feat)
                        <div class="feat-item"><span class="feat-dot"></span>{{ $feat }}</div>
                        @endforeach
                        @if(count($feats) > 4)
                        <div class="feat-item" style="color:#9ca3af;">+{{ count($feats) - 4 }} more features</div>
                        @endif
                    </div>
                    @endif

                    <!-- Apps / Plugins -->
                    <div style="margin-top:.75rem;">
                        <div style="font-size:.68rem;font-weight:700;letter-spacing:.9px;text-transform:uppercase;color:#9ca3af;margin-bottom:.45rem;">
                            {{ $plan->plugins ? 'Included Apps' : 'All Apps' }}
                        </div>
                        @if($planApps->isNotEmpty())
                        <div style="display:flex;flex-wrap:wrap;gap:.35rem;">
                            @foreach($planApps as $pa)
                            <span style="display:inline-flex;align-items:center;gap:.3rem;background:#f8fafc;border:1px solid #e5e7eb;border-radius:6px;padding:.22rem .55rem;font-size:.75rem;color:#374151;font-weight:500;">
                                <i class="{{ $pa->icon }}" style="color:{{ $pa->color }};font-size:.7rem;"></i>
                                {{ $pa->display_name }}
                            </span>
                            @endforeach
                        </div>
                        @else
                        <span style="font-size:.78rem;color:#25d366;font-weight:600;">✓ All active apps included</span>
                        @endif
                    </div>
                </div>

                <div class="plan-footer">
                    <div class="plan-meta">
                        {{ $plan->payment_processor ?: 'No processor' }} ·
                        Created {{ $plan->created_at->format('d M Y') }}
                    </div>
                    <div class="plan-actions">
                        <button class="act-btn act-edit" title="Edit plan" onclick="openEditModal({{ $plan->id }})">
                            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z"/></svg>
                        </button>
                        <button class="act-btn act-del" title="Delete plan" onclick="confirmDelete({{ $plan->id }}, '{{ addslashes($plan->name) }}')">
                            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"/></svg>
                        </button>
                    </div>
                </div>
            </div>
            @endforeach
        </div>

        <!-- TABLE VIEW -->
        <div class="table-section">
            <div class="section-title">Plans Summary</div>
            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Price</th>
                            <th>Period</th>
                            <th>Campaigns</th>
                            <th>Messages</th>
                            <th>Contacts</th>
                            <th>Apps</th>
                            <th>Processor</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    @foreach($plans as $i => $plan)
                    <tr>
                        <td style="color:#9ca3af;font-size:.8rem;">{{ $i+1 }}</td>
                        <td>
                            <div style="font-weight:700;color:#0f0f0f;">{{ $plan->name }}</div>
                            @if($plan->description)
                            <div style="font-size:.75rem;color:#9ca3af;">{{ Str::limit($plan->description,50) }}</div>
                            @endif
                        </td>
                        <td style="font-weight:700;color:#0f0f0f;">${{ number_format($plan->price,2) }}</td>
                        <td><span class="pill" style="background:#f0f9ff;color:#0369a1;">{{ ['1month'=>'1 Month','3months'=>'3 Months','6months'=>'6 Months','1year'=>'1 Year'][$plan->period] ?? $plan->period }}</span></td>
                        <td style="text-align:center;color:{{ $plan->campaigns_limit==0?'#25d366':'inherit' }};">{{ $plan->campaigns_limit == 0 ? 'Unlimited' : $plan->campaigns_limit }}</td>
                        <td style="text-align:center;color:{{ $plan->messages_limit==0?'#25d366':'inherit' }};font-weight:{{ $plan->messages_limit==0?'700':'400' }};">{{ $plan->messages_limit == 0 ? 'Unlimited' : number_format($plan->messages_limit) }}</td>
                        <td style="text-align:center;color:{{ $plan->contacts_limit==0?'#25d366':'inherit' }};">{{ $plan->contacts_limit == 0 ? 'Unlimited' : number_format($plan->contacts_limit) }}</td>
                        <td>
                            @php
                                $tblPluginKeys = $plan->plugins ? array_filter(array_map('trim', explode(',', $plan->plugins))) : [];
                                $tblApps = $plan->plugins ? $apps->whereIn('app_key', $tblPluginKeys) : collect();
                            @endphp
                            @if($tblApps->isNotEmpty())
                                <div style="display:flex;flex-wrap:wrap;gap:.3rem;">
                                @foreach($tblApps as $ta)
                                <span title="{{ $ta->display_name }}" style="display:inline-flex;align-items:center;gap:.25rem;background:#f8fafc;border:1px solid #e5e7eb;border-radius:5px;padding:.18rem .45rem;font-size:.72rem;color:#374151;">
                                    <i class="{{ $ta->icon }}" style="color:{{ $ta->color }};font-size:.65rem;"></i>{{ $ta->display_name }}
                                </span>
                                @endforeach
                                </div>
                            @else
                                <span style="font-size:.78rem;color:#25d366;font-weight:600;">All</span>
                            @endif
                        </td>
                        <td style="color:#6b7280;font-size:.82rem;">{{ $plan->payment_processor ?: '—' }}</td>
                        <td>
                            <span class="pill {{ $plan->is_active ? 'pill-on' : 'pill-off' }}">
                                {{ $plan->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </td>
                        <td>
                            <div style="display:flex;gap:.4rem;">
                                <button class="act-btn act-edit" onclick="openEditModal({{ $plan->id }})">
                                    <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z"/></svg>
                                </button>
                                <button class="act-btn act-del" onclick="confirmDelete({{ $plan->id }},'{{ addslashes($plan->name) }}')">
                                    <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"/></svg>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>
        </div>

        @endif
    </main>
</div>

<!-- ADD PLAN MODAL -->
<div class="modal-backdrop" id="addModal" onclick="closeAddModal(event)">
    <div class="add-modal" onclick="event.stopPropagation()">
        <div class="add-modal-header">
            <h3>Plans Management — Add New Plan</h3>
            <button class="add-modal-close" onclick="closeAddModal()">
                <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </div>

        <form method="POST" action="{{ route('pricing-plans.store') }}" id="addPlanForm">
            @csrf
            <div class="add-modal-body">

                @if($errors->any())
                <div style="background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:.65rem 1rem;border-radius:9px;margin-bottom:1rem;font-size:.82rem;">
                    {{ $errors->first() }}
                </div>
                @endif

                <!-- PLAN INFO -->
                <div class="am-section-head">Plan Information</div>
                <div class="am-grid">
                    <div class="am-group full">
                        <label class="am-label">Name <span style="color:#ef4444">*</span></label>
                        <input type="text" name="name" class="am-input {{ $errors->has('name')?'err':'' }}"
                            placeholder="Plan name" value="{{ old('name') }}" required>
                        @error('name')<span class="am-err">{{ $message }}</span>@enderror
                    </div>
                    <div class="am-group full">
                        <label class="am-label">Description <span class="opt">(optional)</span></label>
                        <textarea name="description" class="am-textarea" placeholder="Plan description...">{{ old('description') }}</textarea>
                    </div>
                    <div class="am-group full">
                        <label class="am-label">Features List <span class="opt">(separate with comma)</span></label>
                        <input type="text" name="features" class="am-input"
                            placeholder="Plan Features comma separated..." value="{{ old('features') }}">
                        <span class="am-hint">e.g. Bulk messaging, Analytics, API access</span>
                    </div>
                    <div class="am-group">
                        <label class="am-label">Price <span style="color:#ef4444">*</span></label>
                        <input type="number" name="price" step="0.01" min="0" class="am-input {{ $errors->has('price')?'err':'' }}"
                            placeholder="0.00" value="{{ old('price', 0) }}" required>
                        @error('price')<span class="am-err">{{ $message }}</span>@enderror
                    </div>
                    <div class="am-group">
                        <label class="am-label">Plan Period <span style="color:#ef4444">*</span></label>
                        <div class="period-toggle">
                            <input type="radio" name="period" id="p_1m" value="1month"  {{ old('period','1month')=='1month' ?'checked':'' }}>
                            <label for="p_1m">1 Month</label>
                            <input type="radio" name="period" id="p_3m" value="3months" {{ old('period')=='3months'?'checked':'' }}>
                            <label for="p_3m">3 Months</label>
                            <input type="radio" name="period" id="p_6m" value="6months" {{ old('period')=='6months'?'checked':'' }}>
                            <label for="p_6m">6 Months</label>
                            <input type="radio" name="period" id="p_1y" value="1year"   {{ old('period')=='1year'  ?'checked':'' }}>
                            <label for="p_1y">1 Year</label>
                        </div>
                    </div>
                    <div class="am-group full">
                        <label class="am-label">Payment Processor <span class="opt">(optional)</span></label>
                        <select name="payment_processor" class="am-select">
                            <option value="">Select payment processor</option>
                            <option value="stripe"  {{ old('payment_processor')=='stripe' ?'selected':'' }}>Stripe</option>
                            <option value="paypal"  {{ old('payment_processor')=='paypal' ?'selected':'' }}>PayPal</option>
                            <option value="razorpay"{{ old('payment_processor')=='razorpay'?'selected':'' }}>Razorpay</option>
                            <option value="manual"  {{ old('payment_processor')=='manual' ?'selected':'' }}>Manual</option>
                        </select>
                    </div>
                </div>

                <!-- PLAN LIMITS -->
                <div class="am-section-head">Plan Limits</div>
                <div class="limits-row">
                    <div class="am-group">
                        <label class="am-label">Campaigns Limit</label>
                        <input type="number" name="campaigns_limit" min="0" class="am-input"
                            placeholder="0" value="{{ old('campaigns_limit', 0) }}">
                        <span class="am-hint">0 = unlimited</span>
                    </div>
                    <div class="am-group">
                        <label class="am-label">Messages Limit</label>
                        <input type="number" name="messages_limit" min="0" class="am-input"
                            placeholder="0" value="{{ old('messages_limit', 0) }}">
                        <span class="am-hint">0 = unlimited</span>
                    </div>
                    <div class="am-group">
                        <label class="am-label">Contacts Limit</label>
                        <input type="number" name="contacts_limit" min="0" class="am-input"
                            placeholder="0" value="{{ old('contacts_limit', 0) }}">
                        <span class="am-hint">0 = unlimited</span>
                    </div>
                </div>

                <!-- PLUGINS -->
                <div class="am-section-head">Plugins</div>
                <div class="am-group">
                    <label class="am-label">Select available apps <span class="opt">(leave empty for all)</span></label>
                    @php $oldPlugins = old('plugins') ? explode(',', old('plugins')) : []; @endphp
                    @if($apps->isEmpty())
                    <div style="font-size:.82rem;color:#9ca3af;padding:.5rem 0;">No active apps found. <a href="{{ route('apps') }}" style="color:#25d366;">Create apps first →</a></div>
                    @else
                    <div class="plugin-chips" id="pluginChips">
                        @foreach($apps as $app)
                        @php $isOldChecked = in_array($app->app_key, $oldPlugins); @endphp
                        <label class="plugin-chip {{ $isOldChecked ? 'selected' : '' }}" data-key="{{ $app->app_key }}">
                            <input type="checkbox" value="{{ $app->app_key }}" {{ $isOldChecked ? 'checked' : '' }}>
                            <i class="{{ $app->icon }}" style="color:{{ $app->color }};font-size:.85rem;"></i>
                            {{ $app->display_name }}
                        </label>
                        @endforeach
                    </div>
                    @endif
                    <input type="hidden" name="plugins" id="pluginsInput" value="{{ old('plugins') }}">
                </div>

            </div>
            <div class="add-modal-footer">
                <button type="button" class="btn-cancel-modal" onclick="closeAddModal()">Cancel</button>
                <button type="submit" class="btn-save">
                    <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    Save Plan
                </button>
            </div>
        </form>
    </div>
</div>

<!-- EDIT PLAN MODAL -->
<div class="modal-backdrop" id="editModal" onclick="closeEditModal(event)">
    <div class="add-modal" onclick="event.stopPropagation()">
        <div class="add-modal-header">
            <h3>Edit Plan</h3>
            <button class="add-modal-close" onclick="closeEditModal()">
                <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </div>
        <form method="POST" id="editPlanForm" action="">
            @csrf @method('PATCH')
            <div class="add-modal-body">

                <!-- PLAN INFO -->
                <div class="am-section-head">Plan Information</div>
                <div class="am-grid">
                    <div class="am-group full">
                        <label class="am-label">Name <span style="color:#ef4444">*</span></label>
                        <input type="text" name="name" id="ep_name" class="am-input" required>
                    </div>
                    <div class="am-group full">
                        <label class="am-label">Description <span class="opt">(optional)</span></label>
                        <textarea name="description" id="ep_desc" class="am-textarea"></textarea>
                    </div>
                    <div class="am-group full">
                        <label class="am-label">Features List <span class="opt">(comma separated)</span></label>
                        <input type="text" name="features" id="ep_features" class="am-input" placeholder="Feature 1, Feature 2, ...">
                    </div>
                    <div class="am-group">
                        <label class="am-label">Price <span style="color:#ef4444">*</span></label>
                        <input type="number" name="price" id="ep_price" step="0.01" min="0" class="am-input" required>
                    </div>
                    <div class="am-group">
                        <label class="am-label">Plan Period <span style="color:#ef4444">*</span></label>
                        <div class="period-toggle">
                            <input type="radio" name="period" id="ep_1m" value="1month"><label for="ep_1m">1 Month</label>
                            <input type="radio" name="period" id="ep_3m" value="3months"><label for="ep_3m">3 Months</label>
                            <input type="radio" name="period" id="ep_6m" value="6months"><label for="ep_6m">6 Months</label>
                            <input type="radio" name="period" id="ep_1y" value="1year"><label for="ep_1y">1 Year</label>
                        </div>
                    </div>
                    <div class="am-group full">
                        <label class="am-label">Payment Processor <span class="opt">(optional)</span></label>
                        <select name="payment_processor" id="ep_processor" class="am-select">
                            <option value="">Select payment processor</option>
                            <option value="stripe">Stripe</option>
                            <option value="paypal">PayPal</option>
                            <option value="razorpay">Razorpay</option>
                            <option value="manual">Manual</option>
                        </select>
                    </div>
                </div>

                <!-- PLAN LIMITS -->
                <div class="am-section-head">Plan Limits</div>
                <div class="limits-row">
                    <div class="am-group">
                        <label class="am-label">Campaigns Limit</label>
                        <input type="number" name="campaigns_limit" id="ep_camp" min="0" class="am-input" placeholder="0">
                        <span class="am-hint">0 = unlimited</span>
                    </div>
                    <div class="am-group">
                        <label class="am-label">Messages Limit</label>
                        <input type="number" name="messages_limit" id="ep_msg" min="0" class="am-input" placeholder="0">
                        <span class="am-hint">0 = unlimited</span>
                    </div>
                    <div class="am-group">
                        <label class="am-label">Contacts Limit</label>
                        <input type="number" name="contacts_limit" id="ep_contact" min="0" class="am-input" placeholder="0">
                        <span class="am-hint">0 = unlimited</span>
                    </div>
                </div>

                <!-- PLUGINS -->
                <div class="am-section-head">Plugins</div>
                <div class="am-group">
                    <label class="am-label">Select available apps <span class="opt">(leave empty for all)</span></label>
                    @if($apps->isEmpty())
                    <div style="font-size:.82rem;color:#9ca3af;padding:.5rem 0;">No active apps found. <a href="{{ route('apps') }}" style="color:#25d366;">Create apps first →</a></div>
                    @else
                    <div class="plugin-chips" id="editPluginChips">
                        @foreach($apps as $app)
                        <label class="plugin-chip" data-key="{{ $app->app_key }}" id="epc_{{ $app->app_key }}">
                            <input type="checkbox" value="{{ $app->app_key }}">
                            <i class="{{ $app->icon }}" style="color:{{ $app->color }};font-size:.85rem;"></i>
                            {{ $app->display_name }}
                        </label>
                        @endforeach
                    </div>
                    @endif
                    <input type="hidden" name="plugins" id="editPluginsInput">
                </div>

            </div>
            <div class="add-modal-footer">
                <button type="button" class="btn-cancel-modal" onclick="closeEditModal()">Cancel</button>
                <button type="submit" class="btn-save">
                    <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    Save Changes
                </button>
            </div>
        </form>
    </div>
</div>

<!-- DELETE MODAL -->
<div class="modal-backdrop" id="deleteModal">
    <div class="del-modal">
        <div style="width:52px;height:52px;background:#fef2f2;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 1rem;">
            <svg width="22" height="22" fill="none" viewBox="0 0 24 24" stroke="#dc2626" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/></svg>
        </div>
        <h3>Delete Plan?</h3>
        <p id="deletePlanText">This cannot be undone.</p>
        <div class="modal-actions">
            <button class="btn-cancel-modal" onclick="document.getElementById('deleteModal').classList.remove('open')">Cancel</button>
            <form id="deletePlanForm" method="POST" style="display:inline;">
                @csrf @method('DELETE')
                <button type="submit" class="btn-del-modal">Yes, Delete</button>
            </form>
        </div>
    </div>
</div>

<script>
    /* ── Add modal ── */
    function openAddModal() {
        document.getElementById('addModal').classList.add('open');
        document.body.style.overflow = 'hidden';
    }
    function closeAddModal(e) {
        if (e && e.target !== document.getElementById('addModal')) return;
        document.getElementById('addModal').classList.remove('open');
        document.body.style.overflow = '';
    }

    @if($errors->any() && old('name') !== null)
    openAddModal();
    @endif

    /* ── Plugin chips ── */
    document.querySelectorAll('.plugin-chip').forEach(chip => {
        chip.addEventListener('click', function(e) {
            e.preventDefault();
            this.classList.toggle('selected');
            const cb = this.querySelector('input[type=checkbox]');
            if (cb) cb.checked = this.classList.contains('selected');
            updatePluginsInput();
        });
    });
    function updatePluginsInput() {
        const selected = [...document.querySelectorAll('.plugin-chip.selected')]
            .map(c => c.getAttribute('data-key')).filter(Boolean);
        document.getElementById('pluginsInput').value = selected.join(',');
    }

    /* ── Delete modal ── */
    function confirmDelete(id, name) {
        document.getElementById('deletePlanText').textContent = 'Delete plan "' + name + '"? This cannot be undone.';
        document.getElementById('deletePlanForm').action = '/pricing-plans/' + id;
        document.getElementById('deleteModal').classList.add('open');
    }

    /* ── Edit modal ── */
    const plansData = @json($plans->keyBy('id'));

    function openEditModal(id) {
        const p = plansData[id];
        if (!p) return;

        document.getElementById('editPlanForm').action = '/pricing-plans/' + id;
        document.getElementById('ep_name').value       = p.name       || '';
        document.getElementById('ep_desc').value       = p.description|| '';
        document.getElementById('ep_features').value  = p.features   || '';
        document.getElementById('ep_price').value      = p.price      || 0;
        document.getElementById('ep_camp').value       = p.campaigns_limit || 0;
        document.getElementById('ep_msg').value        = p.messages_limit  || 0;
        document.getElementById('ep_contact').value    = p.contacts_limit  || 0;

        // Period radio
        const periodMap = {'1month':'ep_1m','3months':'ep_3m','6months':'ep_6m','1year':'ep_1y'};
        Object.values(periodMap).forEach(id => { const el=document.getElementById(id); if(el)el.checked=false; });
        const pid = periodMap[p.period];
        if (pid) document.getElementById(pid).checked = true;

        // Payment processor
        const proc = document.getElementById('ep_processor');
        if (proc) proc.value = p.payment_processor || '';

        // Plugin chips
        const currentPlugins = p.plugins ? p.plugins.split(',').map(s=>s.trim()).filter(Boolean) : [];
        document.querySelectorAll('#editPluginChips .plugin-chip').forEach(chip => {
            const key = chip.getAttribute('data-key');
            const cb  = chip.querySelector('input[type=checkbox]');
            const sel = currentPlugins.includes(key);
            chip.classList.toggle('selected', sel);
            if (cb) cb.checked = sel;
        });
        document.getElementById('editPluginsInput').value = currentPlugins.join(',');

        document.getElementById('editModal').classList.add('open');
        document.body.style.overflow = 'hidden';
    }

    function closeEditModal(e) {
        if (e && e.target !== document.getElementById('editModal')) return;
        document.getElementById('editModal').classList.remove('open');
        document.body.style.overflow = '';
    }

    /* Edit plugin chips */
    document.querySelectorAll('#editPluginChips .plugin-chip').forEach(chip => {
        chip.addEventListener('click', function(e) {
            e.preventDefault();
            this.classList.toggle('selected');
            const cb = this.querySelector('input[type=checkbox]');
            if (cb) cb.checked = this.classList.contains('selected');
            const selected = [...document.querySelectorAll('#editPluginChips .plugin-chip.selected')]
                .map(c => c.getAttribute('data-key')).filter(Boolean);
            document.getElementById('editPluginsInput').value = selected.join(',');
        });
    });

    /* ── Sidebar navigation with exit animation ── */
    document.querySelectorAll('.nav-item').forEach(el => {
        el.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (!href || href === '#') return;
            e.preventDefault();
            const mainEl = document.querySelector('main');
            mainEl.style.cssText = 'margin-left:248px;flex:1;padding:1.75rem 2rem;animation:fadeOut .18s ease both';
            setTimeout(() => { window.location.href = href; }, 180);
        });
    });
</script>
</body>
</html>
