<x-layouts.admin :title="__('Addons')" :subtitle="__('Install and manage :brand add-ons (Instagram, Facebook Messenger, etc.)', ['brand' => \App\Helpers\BrandingHelper::name()])">
    <div class="space-y-6">

        {{-- Flash messages rendered by the admin layout — no duplicate here. --}}

        {{-- Platform license banner — shown ONLY when the MailTrixy
             license file is missing. Fresh installs already have it
             from the installer's verifyLicense step; this banner is
             the recovery path for customers who upgraded an existing
             install without going through the installer.
             Once the customer submits a valid code here, every addon's
             license check flips true on the next render. --}}
        @if(empty($platformLicense))
            <div class="panel p-6 border-2 border-danger/40 bg-danger/5">
                <div class="flex items-start gap-3 mb-3">
                    <svg class="w-5 h-5 text-danger shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" 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>
                        <p class="text-sm font-bold text-danger">{{ __('MailTrixy license is missing on this server.') }}</p>
                        <p class="mt-1 text-xs text-muted">{{ __('Paste your Envato purchase code below. The same code unlocks every addon — you only need to do this once.') }}</p>
                    </div>
                </div>
                <form method="POST" action="{{ route('admin.addons.license') }}" class="flex flex-wrap items-end gap-2">
                    @csrf
                    <div class="flex-1 min-w-[280px]">
                        <label class="sr-only" for="platform-license">{{ __('Envato purchase code') }}</label>
                        <input id="platform-license" type="text" name="purchase_code" required autocomplete="off"
                               spellcheck="false" maxlength="36"
                               pattern="[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"
                               placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
                               class="input-field text-xs font-mono">
                    </div>
                    <button type="submit" class="btn-primary text-xs">{{ __('Verify & Save') }}</button>
                </form>
            </div>
        @else
            {{-- Quiet confirmation banner — same info without taking
                 over the page once everything is in order. --}}
            <div class="panel p-4 bg-emerald-500/5 border border-emerald-500/20 flex items-center gap-3">
                <svg class="w-5 h-5 text-emerald-500 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2"><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>
                <p class="text-xs text-muted">
                    {{ __('MailTrixy licensed to') }}
                    <strong class="text-ink">{{ $platformLicense['envato_buyer'] ?: __('Envato buyer') }}</strong>
                    @if(!empty($platformLicense['verified_at']))
                        {{ __('on') }} {{ \Carbon\Carbon::parse($platformLicense['verified_at'])->toFormattedDateString() }}
                    @endif
                    — {{ __('every addon is unlockable.') }}
                </p>
            </div>
        @endif

        {{-- Upload Panel — only visible when the platform license has
             been verified. Server-side AddonController::upload() also
             refuses unlicensed uploads, but hiding the form removes
             the affordance entirely so the admin isn't confused by an
             input they can't use. --}}
        @if(!empty($platformLicense))
        <div class="panel p-6">
            <div class="flex flex-wrap items-start justify-between gap-4 mb-4">
                <div>
                    <p class="panel-heading">{{ __('Install Addon') }}</p>
                    <p class="mt-2 text-sm text-muted">
                        {{ __('Upload a :brand addon ZIP. The package must contain an addon.json manifest at its root.', ['brand' => \App\Helpers\BrandingHelper::name()]) }}
                    </p>
                </div>
            </div>

            <form method="POST" action="{{ route('admin.addons.upload') }}" enctype="multipart/form-data"
                  class="grid gap-4 sm:grid-cols-[1fr_auto]">
                @csrf
                <div>
                    <label class="sr-only" for="addon_zip">{{ __('Addon ZIP') }}</label>
                    <input id="addon_zip" type="file" name="addon_zip" accept=".zip" required
                           class="input-field file:mr-3 file:py-1.5 file:px-3 file:border-0 file:rounded-md file:bg-primary-600 file:text-white file:text-sm">
                    @error('addon_zip')
                        <p class="text-xs text-danger mt-1">{{ $message }}</p>
                    @enderror
                    <p class="text-xs text-muted mt-2">
                        {{ __('Max 50 MB. Only ZIP files containing an addon.json manifest are accepted. Uploading code runs with full application privileges — only install addons from sources you trust.') }}
                    </p>
                </div>
                <div class="flex items-start">
                    <button type="submit" class="btn-primary">{{ __('Upload & Install') }}</button>
                </div>
            </form>
        </div>
        @endif

        {{-- Installed Addons --}}
        <div class="panel p-0 overflow-hidden">
            <div class="px-6 py-4 border-b border-border">
                <p class="panel-heading">{{ __('Installed Addons') }}</p>
                <p class="mt-1 text-xs text-muted">
                    {{ __('Activate an addon to register its service provider, run its migrations, and mount its routes. Deactivating leaves the files on disk but skips the boot step.') }}
                </p>
            </div>

            @if($addons->isEmpty())
                <div class="px-6 py-12 text-center">
                    <p class="text-sm text-muted">
                        {{ __('No addons installed yet. Upload a ZIP above to get started.') }}
                    </p>
                </div>
            @else
                <div class="divide-y divide-border">
                    @php
                        // Every addon inherits its licensed state from the
                        // platform-wide MailTrixy license. Hoisted out of
                        // the loop because the value never changes per row.
                        $__licensed = !empty($platformLicense);
                    @endphp
                    @foreach($addons as $addon)
                        <div class="px-6 py-5 flex flex-wrap items-start gap-4 justify-between">
                            <div class="min-w-0 flex-1">
                                <div class="flex items-center gap-2 flex-wrap">
                                    <p class="text-sm font-semibold text-ink truncate">{{ $addon->name }}</p>
                                    <span class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-surface-2 text-muted">v{{ $addon->version }}</span>
                                    @if($addon->isActive())
                                        <span class="px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-success/10 text-success">{{ __('Active') }}</span>
                                    @else
                                        <span class="px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-muted/10 text-muted">{{ __('Inactive') }}</span>
                                    @endif
                                </div>
                                @if($addon->description)
                                    <p class="text-xs text-muted mt-1 line-clamp-2">{{ $addon->description }}</p>
                                @endif
                                <div class="mt-2 flex flex-wrap items-center gap-3 text-[11px] text-muted">
                                    <span><span class="font-medium">{{ __('Slug') }}:</span> {{ $addon->slug }}</span>
                                    @if($addon->author)
                                        <span>
                                            <span class="font-medium">{{ __('Author') }}:</span>
                                            @if($addon->author_url)
                                                <a href="{{ $addon->author_url }}" target="_blank" rel="noopener" class="text-primary-600 hover:underline">{{ $addon->author }}</a>
                                            @else
                                                {{ $addon->author }}
                                            @endif
                                        </span>
                                    @endif
                                    @if($addon->installed_at)
                                        <span><span class="font-medium">{{ __('Installed') }}:</span> {{ $addon->installed_at->diffForHumans() }}</span>
                                    @endif
                                </div>

                            </div>

                            {{-- Action bar — Settings | Deactivate/Activate | Uninstall.
                                 Settings is a proper button (was a tiny text link below
                                 the description, which most users missed). It pulls from
                                 the addon's manifest `settings_url` so each addon can
                                 ship its own admin UI without touching the core sidebar. --}}
                            @php
                                // The manifest stores a root-relative path like
                                // "/admin/addons/instagram/settings". Wrap it with
                                // url() so it picks up APP_URL — installs running
                                // out of a subfolder (e.g. https://example.com/
                                // mailtrixy/public/) would otherwise navigate to
                                // https://example.com/admin/addons/… which is
                                // OUTSIDE the MailTrixy install and 404s.
                                $settingsUrl = $addon->manifest['settings_url'] ?? null;
                                if ($settingsUrl) {
                                    $settingsUrl = url($settingsUrl);
                                }
                                // The addon's ServiceProvider only registers routes when
                                // its files exist under addons/{slug}/. If a customer
                                // restored a DB backup without re-uploading the addon
                                // ZIP — or the disk failed — the row stays active but
                                // the folder is gone. Rendering the Settings button
                                // anyway sends them straight to a 404. Detect the
                                // missing-files state up-front so we show a helpful
                                // "Reinstall files" banner instead.
                                $addonFolderExists = is_dir(base_path('addons/'.$addon->slug));
                            @endphp
                            <div class="flex items-center gap-2 shrink-0">
                                @if(!$addonFolderExists)
                                    {{-- Files missing — no route was registered, so the
                                         Settings URL would 404. Replace the button
                                         with a clear status pill that links to the
                                         upload UI at the top of the page. --}}
                                    <span class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold rounded-lg bg-danger/10 text-danger border border-danger/20" title="{{ __('Addon row is active but files are missing under addons/'.$addon->slug.'. Re-upload the addon ZIP to restore it.') }}">
                                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/></svg>
                                        {{ __('Files missing — reinstall') }}
                                    </span>
                                @elseif($settingsUrl && $addon->isActive())
                                    <a href="{{ $settingsUrl }}" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold rounded-lg bg-brand text-white hover:bg-brand-strong transition">
                                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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.066 2.573c1.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.573 1.066c-.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.066-2.573c-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" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                        {{ __('Settings') }}
                                    </a>
                                @endif
                                @if($addon->isActive())
                                    <form method="POST" action="{{ route('admin.addons.deactivate', $addon) }}">
                                        @csrf
                                        <button type="submit" class="btn-secondary text-xs">{{ __('Deactivate') }}</button>
                                    </form>
                                @elseif($__licensed)
                                    {{-- Licensed + inactive → Activate is enabled. --}}
                                    <form method="POST" action="{{ route('admin.addons.activate', $addon) }}">
                                        @csrf
                                        <button type="submit" class="btn-primary text-xs">{{ __('Activate') }}</button>
                                    </form>
                                @else
                                    {{-- Unlicensed → Activate is disabled and we
                                         tell the admin to enter a code below.
                                         AddonController::activate ALSO rejects
                                         this server-side, so this is purely
                                         UX affordance. --}}
                                    <button type="button" disabled
                                            class="btn-primary text-xs opacity-50 cursor-not-allowed"
                                            title="{{ __('Enter your Envato purchase code below to unlock activation.') }}">
                                        {{ __('Activate') }}
                                    </button>
                                @endif
                                <form method="POST" action="{{ route('admin.addons.uninstall', $addon) }}"
                                      onsubmit="return confirm('{{ __('Uninstall this addon? Files will be deleted. Database tables created by the addon will be left in place.') }}');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn-danger text-xs">{{ __('Uninstall') }}</button>
                                </form>
                            </div>

                            {{-- Per-row license affordance removed. The
                                 single platform-wide banner at the top of
                                 the page handles unlicensed installs;
                                 once that's verified, every addon row
                                 just shows the Activate button. --}}
                        </div>
                    @endforeach
                </div>
            @endif
        </div>
    </div>
</x-layouts.admin>
