<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Apps — 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 ── */
        .page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:1.75rem; }
        .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; }

        /* ── SECTION HEADER ── */
        .section-head { display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem; padding-bottom:.75rem; border-bottom:2px solid; }
        .section-head.free-head { border-color:#25d366; }
        .section-head.paid-head { border-color:#f59e0b; }
        .sh-left { display:flex; align-items:center; gap:.75rem; }
        .sh-icon { font-size:1.3rem; }
        .sh-title { font-size:1rem; font-weight:800; color:#0f0f0f; }
        .sh-sub   { font-size:.78rem; color:#9ca3af; margin-top:1px; }
        .sh-count { font-size:.82rem; font-weight:700; }
        .sh-count.free-c { color:#25d366; }
        .sh-count.paid-c { color:#f59e0b; }

        /* ── APPS GRID ── */
        .apps-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:1rem; margin-bottom:2.5rem; }
        @media(max-width:1400px){ .apps-grid{ grid-template-columns:repeat(3,1fr); } }

        /* ── APP CARD ── */
        .app-card { background:#fff; border-radius:14px; border:1.5px solid #e5e7eb; padding:1.2rem 1.3rem 1rem; display:flex; flex-direction:column; gap:.75rem; transition:box-shadow .2s,transform .2s,border-color .2s; }
        .app-card:hover { box-shadow:0 6px 24px rgba(0,0,0,.1); transform:translateY(-2px); border-color:#d1fae5; }
        .app-card.paid-card { border-color:#fde68a; }
        .app-card.paid-card:hover { border-color:#f59e0b; }

        .card-top { display:flex; align-items:flex-start; gap:.85rem; }
        .app-icon-wrap { width:48px; height:48px; border-radius:12px; display:flex; align-items:center; justify-content:center; flex-shrink:0; font-size:1.25rem; }
        .card-info { flex:1; min-width:0; }
        .card-name { font-size:.92rem; font-weight:800; color:#0f0f0f; display:flex; align-items:center; gap:.5rem; flex-wrap:wrap; }
        .free-badge { display:inline-flex; align-items:center; gap:3px; background:#f0fdf4; color:#15803d; font-size:.68rem; font-weight:700; padding:.18rem .5rem; border-radius:6px; }
        .paid-badge { display:inline-flex; align-items:center; gap:3px; background:#fffbeb; color:#92400e; font-size:.68rem; font-weight:700; padding:.18rem .5rem; border-radius:6px; }
        .card-category { font-size:.7rem; font-weight:700; letter-spacing:.8px; text-transform:uppercase; color:#9ca3af; margin-top:2px; }

        .card-desc { font-size:.8rem; color:#6b7280; line-height:1.55; flex:1; }

        .card-footer { display:flex; align-items:center; justify-content:space-between; padding-top:.6rem; border-top:1px solid #f8fafc; }
        .status-dot { display:flex; align-items:center; gap:.4rem; font-size:.78rem; font-weight:600; }
        .dot { width:8px; height:8px; border-radius:50%; }
        .dot-on  { background:#22c55e; }
        .dot-off { background:#d1d5db; }
        .status-on  { color:#15803d; }
        .status-off { color:#9ca3af; }

        .card-actions { display:flex; align-items:center; gap:.4rem; }
        .act-open { display:inline-flex; align-items:center; gap:.3rem; font-size:.75rem; font-weight:600; color:#374151; text-decoration:none; padding:.3rem .65rem; border-radius:7px; border:1px solid #e5e7eb; background:#fff; cursor:pointer; transition:.15s; }
        .act-open:hover { border-color:#9ca3af; }
        .act-open svg { width:12px; height:12px; }
        .act-disable { font-size:.75rem; font-weight:600; color:#374151; padding:.3rem .65rem; border-radius:7px; border:1px solid #e5e7eb; background:#fff; cursor:pointer; transition:.15s; }
        .act-disable:hover { border-color:#ef4444; color:#ef4444; }
        .act-get { font-size:.75rem; font-weight:700; color:#fff; padding:.3rem .85rem; border-radius:7px; border:none; background:#25d366; cursor:pointer; transition:.15s; }
        .act-get:hover { background:#1db954; }
        .act-del { display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; border-radius:7px; border:none; background:#fef2f2; color:#dc2626; cursor:pointer; font-size:.75rem; transition:.15s; }
        .act-del:hover { background:#fee2e2; }
        .act-upload { display:inline-flex; align-items:center; gap:.3rem; font-size:.72rem; font-weight:600; color:#6366f1; padding:.28rem .6rem; border-radius:7px; border:1.5px solid #e0e7ff; background:#eef2ff; cursor:pointer; transition:.15s; white-space:nowrap; }
        .act-upload:hover { background:#e0e7ff; border-color:#6366f1; }
        .act-get-disabled { font-size:.75rem; font-weight:700; color:#9ca3af; padding:.3rem .85rem; border-radius:7px; border:1.5px dashed #d1d5db; background:#f9fafb; cursor:not-allowed; }

        /* Module badge */
        .module-row { display:flex; align-items:center; justify-content:space-between; padding:.45rem .65rem; border-radius:8px; margin-bottom:.1rem; }
        .module-row.mod-ok   { background:#f0fdf4; }
        .module-row.mod-miss { background:#fff7ed; }
        .mod-badge { display:flex; align-items:center; gap:.35rem; font-size:.72rem; font-weight:700; }
        .mod-badge.ok   { color:#15803d; }
        .mod-badge.miss { color:#c2410c; }

        /* Empty state */
        .empty-section { background:#fff; border-radius:12px; padding:2.5rem; text-align:center; color:#9ca3af; font-size:.88rem; border:1.5px dashed #e5e7eb; }

        /* ── 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:640px; 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)} }

        .modal-header { display:flex; align-items:flex-start; justify-content:space-between; padding:1.3rem 1.6rem; border-bottom:1px solid #f1f5f9; }
        .modal-header h3 { font-size:1.05rem; font-weight:800; color:#0f0f0f; }
        .modal-header p  { font-size:.8rem; color:#9ca3af; margin-top:2px; }
        .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; flex-shrink:0; }
        .modal-close:hover { background:#e2e8f0; color:#0f0f0f; }

        .modal-body { padding:1.5rem 1.6rem; }
        .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-label { font-size:.78rem; font-weight:600; color:#374151; }
        .am-hint  { font-size:.72rem; color:#9ca3af; }
        .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:80px; }
        .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; }

        /* Icon preview row */
        .icon-preview-row { display:flex; align-items:center; gap:.75rem; }
        .icon-preview { width:44px; height:44px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:1.2rem; border:1.5px solid #e5e7eb; flex-shrink:0; transition:.2s; }
        .icon-preview-row .am-input { flex:1; }

        /* Color row */
        .color-row { display:flex; align-items:center; gap:.6rem; }
        .color-swatch { width:44px; height:44px; border-radius:10px; border:1.5px solid #e5e7eb; cursor:pointer; flex-shrink:0; padding:0; overflow:hidden; }
        .color-swatch input[type=color] { width:100%; height:100%; border:none; cursor:pointer; padding:0; background:none; }
        .color-row .am-input { flex:1; }

        /* Paid toggle */
        .paid-toggle-row { background:#f8fafc; border-radius:10px; padding:.85rem 1rem; display:flex; align-items:center; justify-content:space-between; border:1.5px solid #e5e7eb; cursor:pointer; margin-top:.5rem; }
        .paid-toggle-label { display:flex; align-items:center; gap:.6rem; font-size:.88rem; font-weight:600; color:#374151; }
        .toggle-switch { position:relative; width:44px; height:24px; }
        .toggle-switch input { opacity:0; width:0; height:0; }
        .toggle-slider { position:absolute; inset:0; border-radius:24px; background:#e5e7eb; transition:.2s; cursor:pointer; }
        .toggle-slider::before { content:''; position:absolute; width:18px; height:18px; left:3px; bottom:3px; border-radius:50%; background:#fff; transition:.2s; }
        .toggle-switch input:checked + .toggle-slider { background:#25d366; }
        .toggle-switch input:checked + .toggle-slider::before { transform:translateX(20px); }

        .price-fields { display:grid; grid-template-columns:1fr 1fr; gap:.9rem; margin-top:.9rem; }
        .price-fields.hidden { display:none; }

        .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 { 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; 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 { background:#ef4444; color:#fff; border:none; padding:.65rem 1.4rem; border-radius:9px; font-size:.88rem; font-weight:700; cursor:pointer; }
    </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">
            <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 active">
            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z"/></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
        @if(session('error'))
        <div style="background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:.7rem 1rem;border-radius:9px;margin-bottom:1.25rem;font-size:.85rem;font-weight:600;">
            ✗ {{ session('error') }}
        </div>
        @endif

        <div class="page-header">
            <div>
                <h1>Apps</h1>
                <p>Manage available apps and integrations for your CRM</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 New App
            </button>
        </div>

        <!-- FREE APPS -->
        <div class="section-head free-head">
            <div class="sh-left">
                <span class="sh-icon">🎁</span>
                <div>
                    <div class="sh-title">Free Apps</div>
                    <div class="sh-sub">No payment required — enable instantly</div>
                </div>
            </div>
            <span class="sh-count free-c">{{ $freeApps->count() }} apps</span>
        </div>

        @if($freeApps->isEmpty())
        <div class="empty-section" style="margin-bottom:2.5rem;">No free apps yet. Click "Add New App" to create one.</div>
        @else
        <div class="apps-grid">
            @foreach($freeApps as $app)
            @php $modInstalled = is_dir(base_path('modules/' . $app->app_key)); @endphp
            <div class="app-card">
                <div class="card-top">
                    <div class="app-icon-wrap" style="background:{{ $app->color }}22; color:{{ $app->color }};">
                        <i class="{{ $app->icon }}"></i>
                    </div>
                    <div class="card-info">
                        <div class="card-name">
                            {{ $app->display_name }}
                            <span class="free-badge">✓ Free</span>
                        </div>
                        <div class="card-category">{{ strtoupper($app->category ?? 'GENERAL') }}</div>
                    </div>
                </div>
                <div class="card-desc">{{ $app->description ?? 'No description provided.' }}</div>

                <div class="module-row {{ $modInstalled ? 'mod-ok' : 'mod-miss' }}">
                    <span class="mod-badge {{ $modInstalled ? 'ok' : 'miss' }}">
                        @if($modInstalled)
                            <i class="fas fa-check-circle"></i> Module Ready
                        @else
                            <i class="fas fa-exclamation-triangle"></i> No Module
                        @endif
                    </span>
                    <button class="act-upload" onclick="openUploadModal({{ $app->id }}, '{{ addslashes($app->display_name) }}')">
                        <i class="fas fa-upload"></i> Upload
                    </button>
                </div>

                <div class="card-footer">
                    <div class="status-dot {{ $app->is_active ? 'status-on' : 'status-off' }}">
                        <span class="dot {{ $app->is_active ? 'dot-on' : 'dot-off' }}"></span>
                        {{ $app->is_active ? 'Enabled' : 'Not enabled' }}
                    </div>
                    <div class="card-actions">
                        @if($app->page_link)
                        <a href="{{ $app->page_link }}" class="act-open" target="_blank">
                            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"/></svg>
                            Open
                        </a>
                        @endif
                        @if($app->is_active)
                        <form method="POST" action="{{ route('apps.toggle', $app) }}" style="display:inline;">
                            @csrf @method('PATCH')
                            <button type="submit" class="act-disable">Disable</button>
                        </form>
                        @elseif($modInstalled)
                        <form method="POST" action="{{ route('apps.toggle', $app) }}" style="display:inline;">
                            @csrf @method('PATCH')
                            <button type="submit" class="act-get">Get App</button>
                        </form>
                        @else
                        <span class="act-get-disabled" title="Upload module to activate">Get App</span>
                        @endif
                        <button class="act-del" onclick="confirmDelete({{ $app->id }}, '{{ addslashes($app->display_name) }}')" title="Delete">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
            @endforeach
        </div>
        @endif

        <!-- PREMIUM APPS -->
        <div class="section-head paid-head">
            <div class="sh-left">
                <span class="sh-icon">👑</span>
                <div>
                    <div class="sh-title">Premium Apps</div>
                    <div class="sh-sub">Unlock powerful features with a subscription</div>
                </div>
            </div>
            <span class="sh-count paid-c">{{ $premiumApps->count() }} apps</span>
        </div>

        @if($premiumApps->isEmpty())
        <div class="empty-section">No premium apps yet. Click "Add New App" and enable "Paid App" to create one.</div>
        @else
        <div class="apps-grid">
            @foreach($premiumApps as $app)
            @php $modInstalled = is_dir(base_path('modules/' . $app->app_key)); @endphp
            <div class="app-card paid-card">
                <div class="card-top">
                    <div class="app-icon-wrap" style="background:{{ $app->color }}22; color:{{ $app->color }};">
                        <i class="{{ $app->icon }}"></i>
                    </div>
                    <div class="card-info">
                        <div class="card-name">
                            {{ $app->display_name }}
                            <span class="paid-badge">🔒 ${{ number_format($app->price,2) }}/mo</span>
                        </div>
                        <div class="card-category">{{ strtoupper($app->category ?? 'PREMIUM') }}</div>
                    </div>
                </div>
                <div class="card-desc">{{ $app->description ?? 'No description provided.' }}</div>

                <div class="module-row {{ $modInstalled ? 'mod-ok' : 'mod-miss' }}">
                    <span class="mod-badge {{ $modInstalled ? 'ok' : 'miss' }}">
                        @if($modInstalled)
                            <i class="fas fa-check-circle"></i> Module Ready
                        @else
                            <i class="fas fa-exclamation-triangle"></i> No Module
                        @endif
                    </span>
                    <button class="act-upload" onclick="openUploadModal({{ $app->id }}, '{{ addslashes($app->display_name) }}')">
                        <i class="fas fa-upload"></i> Upload
                    </button>
                </div>

                <div class="card-footer">
                    <div class="status-dot {{ $app->is_active ? 'status-on' : 'status-off' }}">
                        <span class="dot {{ $app->is_active ? 'dot-on' : 'dot-off' }}"></span>
                        {{ $app->is_active ? 'Enabled' : 'Not enabled' }}
                    </div>
                    <div class="card-actions">
                        @if($app->page_link)
                        <a href="{{ $app->page_link }}" class="act-open" target="_blank">
                            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"/></svg>
                            Open
                        </a>
                        @endif
                        @if($app->is_active)
                        <form method="POST" action="{{ route('apps.toggle', $app) }}" style="display:inline;">
                            @csrf @method('PATCH')
                            <button type="submit" class="act-disable">Disable</button>
                        </form>
                        @elseif($modInstalled)
                        <form method="POST" action="{{ route('apps.toggle', $app) }}" style="display:inline;">
                            @csrf @method('PATCH')
                            <button type="submit" class="act-get">Get App</button>
                        </form>
                        @else
                        <span class="act-get-disabled" title="Upload module to activate">Get App</span>
                        @endif
                        <button class="act-del" onclick="confirmDelete({{ $app->id }}, '{{ addslashes($app->display_name) }}')" title="Delete">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
            @endforeach
        </div>
        @endif

    </main>
</div>

<!-- ADD APP MODAL -->
<div class="modal-backdrop" id="addModal" onclick="closeAddModal(event)">
    <div class="add-modal" onclick="event.stopPropagation()">
        <div class="modal-header">
            <div>
                <h3>Add New App</h3>
                <p>Create a new app in the catalog</p>
            </div>
            <button class="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('apps.store') }}">
            @csrf
            <div class="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

                <div class="am-grid">
                    <div class="am-group">
                        <label class="am-label">APP KEY <span style="color:#ef4444">*</span></label>
                        <input type="text" name="app_key" class="am-input {{ $errors->has('app_key')?'err':'' }}"
                            placeholder="e.g. my_app" value="{{ old('app_key') }}" required>
                        <span class="am-hint">Unique slug, lowercase, no spaces</span>
                        @error('app_key')<span class="am-err">{{ $message }}</span>@enderror
                    </div>
                    <div class="am-group">
                        <label class="am-label">DISPLAY NAME <span style="color:#ef4444">*</span></label>
                        <input type="text" name="display_name" class="am-input {{ $errors->has('display_name')?'err':'' }}"
                            placeholder="My App" value="{{ old('display_name') }}" required>
                        @error('display_name')<span class="am-err">{{ $message }}</span>@enderror
                    </div>
                    <div class="am-group full">
                        <label class="am-label">DESCRIPTION</label>
                        <textarea name="description" class="am-textarea" placeholder="Short description shown to users...">{{ old('description') }}</textarea>
                    </div>
                    <div class="am-group">
                        <label class="am-label">FONTAWESOME ICON</label>
                        <div class="icon-preview-row">
                            <div class="icon-preview" id="iconPreview" style="background:#6d717522;color:#6d7175;">
                                <i class="fas fa-puzzle-piece" id="iconPreviewI"></i>
                            </div>
                            <input type="text" name="icon" id="iconInput" class="am-input"
                                placeholder="fas fa-puzzle-piece" value="{{ old('icon','fas fa-puzzle-piece') }}"
                                oninput="updateIconPreview(this.value)">
                        </div>
                        <span class="am-hint">FontAwesome class, e.g. fas fa-star</span>
                    </div>
                    <div class="am-group">
                        <label class="am-label">COLOR</label>
                        <div class="color-row">
                            <div class="color-swatch">
                                <input type="color" id="colorPicker" value="{{ old('color','#6d7175') }}"
                                    oninput="syncColor(this.value)">
                            </div>
                            <input type="text" name="color" id="colorInput" class="am-input"
                                placeholder="#6d7175" value="{{ old('color','#6d7175') }}"
                                oninput="syncColorFromText(this.value)">
                        </div>
                    </div>
                    <div class="am-group">
                        <label class="am-label">CATEGORY</label>
                        <input type="text" name="category" class="am-input"
                            placeholder="e.g. Automation" value="{{ old('category') }}">
                    </div>
                    <div class="am-group">
                        <label class="am-label">PAGE LINK</label>
                        <input type="text" name="page_link" class="am-input"
                            placeholder="orders.php" value="{{ old('page_link') }}">
                        <span class="am-hint">Relative URL in user app directory</span>
                    </div>
                </div>

                <!-- Paid toggle -->
                <label class="paid-toggle-row" for="isPaidToggle" style="margin-top:.9rem;">
                    <div class="paid-toggle-label">
                        <span>🏷️</span> Paid App
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" id="isPaidToggle" name="is_paid" value="1"
                            {{ old('is_paid') ? 'checked' : '' }}
                            onchange="togglePriceFields(this.checked)">
                        <span class="toggle-slider"></span>
                    </label>
                </label>

                <div class="price-fields {{ old('is_paid') ? '' : 'hidden' }}" id="priceFields">
                    <div class="am-group">
                        <label class="am-label">PRICE</label>
                        <input type="number" name="price" step="0.01" min="0" class="am-input"
                            placeholder="0.00" value="{{ old('price', 0) }}">
                    </div>
                    <div class="am-group">
                        <label class="am-label">CURRENCY</label>
                        <input type="text" name="currency" class="am-input"
                            placeholder="USD" value="{{ old('currency','USD') }}">
                    </div>
                </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn-cancel" 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 App
                </button>
            </div>
        </form>
    </div>
</div>

<!-- UPLOAD MODULE MODAL -->
<div class="modal-backdrop" id="uploadModal" onclick="closeUploadModal(event)">
    <div class="add-modal" style="max-width:480px;" onclick="event.stopPropagation()">
        <div class="modal-header">
            <div>
                <h3>Upload Module</h3>
                <p id="uploadModalSubtitle">Upload a ZIP file to install the module</p>
            </div>
            <button class="modal-close" onclick="closeUploadModal()">
                <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 id="uploadForm" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="modal-body">
                <div class="am-group">
                    <label class="am-label">MODULE ZIP FILE <span style="color:#ef4444">*</span></label>
                    <div style="border:2px dashed #e5e7eb;border-radius:12px;padding:2rem;text-align:center;transition:.2s;cursor:pointer;position:relative;"
                         id="dropZone"
                         ondragover="event.preventDefault();this.style.borderColor='#6366f1';this.style.background='#eef2ff';"
                         ondragleave="this.style.borderColor='#e5e7eb';this.style.background='';"
                         ondrop="handleDrop(event)"
                         onclick="document.getElementById('moduleZipInput').click()">
                        <i class="fas fa-file-zipper" style="font-size:2rem;color:#6366f1;margin-bottom:.75rem;display:block;"></i>
                        <div style="font-size:.88rem;font-weight:600;color:#374151;" id="dropLabel">Click or drag & drop a ZIP file here</div>
                        <div style="font-size:.75rem;color:#9ca3af;margin-top:.3rem;">Max 50 MB — .zip only</div>
                        <input type="file" id="moduleZipInput" name="module_zip" accept=".zip" style="position:absolute;inset:0;opacity:0;cursor:pointer;" onchange="onZipSelected(this)">
                    </div>
                    <span class="am-hint" style="margin-top:.35rem;display:block;">The ZIP contents will be extracted to <code style="background:#f1f5f9;padding:.1rem .4rem;border-radius:4px;font-size:.78rem;">modules/{app_key}/</code></span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-cancel" onclick="closeUploadModal()">Cancel</button>
                <button type="submit" class="btn-save" id="uploadSubmitBtn" disabled style="opacity:.5;cursor:not-allowed;">
                    <i class="fas fa-upload" style="font-size:.8rem;"></i>
                    Install Module
                </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 App?</h3>
        <p id="deleteText">This cannot be undone.</p>
        <div class="modal-actions">
            <button class="btn-cancel" onclick="document.getElementById('deleteModal').classList.remove('open')">Cancel</button>
            <form id="deleteForm" method="POST" style="display:inline;">
                @csrf @method('DELETE')
                <button type="submit" class="btn-del">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('app_key') !== null) openAddModal(); @endif

    /* Icon preview */
    function updateIconPreview(val) {
        const el = document.getElementById('iconPreviewI');
        el.className = val || 'fas fa-puzzle-piece';
        const color = document.getElementById('colorInput').value || '#6d7175';
        document.getElementById('iconPreview').style.color = color;
        document.getElementById('iconPreview').style.background = color + '22';
    }

    /* Color sync */
    function syncColor(val) {
        document.getElementById('colorInput').value = val;
        updateIconPreview(document.getElementById('iconInput').value);
    }
    function syncColorFromText(val) {
        if (/^#[0-9a-fA-F]{6}$/.test(val)) {
            document.getElementById('colorPicker').value = val;
            updateIconPreview(document.getElementById('iconInput').value);
        }
    }

    /* Paid toggle */
    function togglePriceFields(checked) {
        document.getElementById('priceFields').classList.toggle('hidden', !checked);
    }

    /* Upload module modal */
    function openUploadModal(appId, appName) {
        document.getElementById('uploadModalSubtitle').textContent = 'Installing module for: ' + appName;
        document.getElementById('uploadForm').action = '/apps/' + appId + '/upload-module';
        document.getElementById('moduleZipInput').value = '';
        document.getElementById('dropLabel').textContent = 'Click or drag & drop a ZIP file here';
        const btn = document.getElementById('uploadSubmitBtn');
        btn.disabled = true; btn.style.opacity = '.5'; btn.style.cursor = 'not-allowed';
        document.getElementById('dropZone').style.borderColor = '#e5e7eb';
        document.getElementById('dropZone').style.background = '';
        document.getElementById('uploadModal').classList.add('open');
        document.body.style.overflow = 'hidden';
    }
    function closeUploadModal(e) {
        if (e && e.target !== document.getElementById('uploadModal')) return;
        document.getElementById('uploadModal').classList.remove('open');
        document.body.style.overflow = '';
    }
    function onZipSelected(input) {
        const file = input.files[0];
        if (!file) return;
        document.getElementById('dropLabel').textContent = '📦 ' + file.name;
        document.getElementById('dropZone').style.borderColor = '#6366f1';
        document.getElementById('dropZone').style.background = '#eef2ff';
        const btn = document.getElementById('uploadSubmitBtn');
        btn.disabled = false; btn.style.opacity = '1'; btn.style.cursor = 'pointer';
    }
    function handleDrop(e) {
        e.preventDefault();
        document.getElementById('dropZone').style.borderColor = '#e5e7eb';
        document.getElementById('dropZone').style.background = '';
        const file = e.dataTransfer.files[0];
        if (!file) return;
        const input = document.getElementById('moduleZipInput');
        const dt = new DataTransfer();
        dt.items.add(file);
        input.files = dt.files;
        onZipSelected(input);
    }

    /* Delete */
    function confirmDelete(id, name) {
        document.getElementById('deleteText').textContent = 'Delete app "' + name + '"? This cannot be undone.';
        document.getElementById('deleteForm').action = '/apps/' + id;
        document.getElementById('deleteModal').classList.add('open');
    }

    /* Sidebar nav */
    document.querySelectorAll('.nav-item').forEach(el => {
        el.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (!href || href === '#') return;
            e.preventDefault();
            document.querySelector('main').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>
