<?php

namespace Components\Ui;

use Components\Base;
use Components\Button;
use Components\Form\Input;
use Components\Router;
use Components\Ui\FilterPills;
use Components\Models\Audience;

class CalendarSubscribe extends Base
{
    /**
     * @param array{
     *   token: string,
     *   filter: string,
     *   baseUrl: string,
     *   rotateUrl: string,
     *   labels: array<string, string>
     * } $opts
     */
    public static function render(array $opts): string
    {
        $token = $opts['token'];
        $filter = $opts['filter'];
        $baseUrl = $opts['baseUrl'];
        $rotateUrl = $opts['rotateUrl'];
        $labels = $opts['labels'];

        $labelsJson = self::h(json_encode($labels), false);
        $filterJson = self::h(json_encode($filter), false);
        $baseUrlJson = self::h(json_encode($baseUrl), false);
        $tokenJson = self::h(json_encode($token), false);

        $title = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_TITLE', 'Subscribe to Calendar'));
        $desc = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_DESC', 'Sync MailBeez events with your personal calendar (Google, Apple, Outlook).'));
        $filterLabel = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_FILTER_LABEL', 'Which MailBeez mailings do you want to see in your calendar?'));
        $quickSetupTitle = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_QUICK_SETUP_TITLE', 'Quick setup'));
        $quickSetupDesc = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_QUICK_SETUP_DESC', 'Opens the calendar app and sets up the automatic subscription.'));
        $quickSetupSub = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_QUICK_SETUP_SUB', 'Opens the calendar app and sets up the automatic subscription.'));
        $openAppLabel = mh_lng('UI_CALENDAR_SUBSCRIBE_OPEN_APP', 'Open in Calendar App');
        $copyLinkLabel = mh_lng('UI_CALENDAR_SUBSCRIBE_COPY', 'Copy');
        $advancedSettingsLabel = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_ADVANCED_SETTINGS', 'Advanced Settings'));
        $webcalLabel = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_WEBCAL_LABEL', 'Webcal Link (Auto-sync)'));
        $httpsLabel = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_HTTPS_LABEL', 'HTTPS Link (Fallback)'));
        $securityTitle = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_SECURITY_TITLE', 'Security'));
        $securityDesc = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_SECURITY_DESC', 'Generate a new private calendar link. If a team member leaves the team, renew the link to avoid unauthorized access. Old links will immediately stop working.'));
        $securityRenewLabel = mh_lng('UI_CALENDAR_SUBSCRIBE_SECURITY_RENEW', 'Renew calendar link');
        $closeLabel = mh_lng('UI_CLOSE', 'Close');
        $rotateConfirm = self::h(mh_lng('UI_CALENDAR_SUBSCRIBE_ROTATE_CONFIRM', 'Renew calendar link?'));
        $copiedLabel = mh_lng('UI_COPIED', 'Copied.');
        $badgeNewsletter = Audience::getBadgeHtml('newsletter');
        $badgeAutomations = Audience::getBadgeHtml('automations');
        $badgeFilter = '<div x-show="filter === \'newsletter\'" class="inline-flex ml-2">' . $badgeNewsletter . '</div>'
            . '<div x-show="filter === \'automations\'" class="inline-flex ml-2">' . $badgeAutomations . '</div>';

        $iconCalendar = self::SVG_OUTLINE_CALENDAR_ADD;
        $iconChevronDown = '<svg class="size-4 text-secondary/40" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m6 9 6 6 6-6"/></svg>';

        ob_start();
        ?>
        <span hx-swap-oob="innerHTML:#config-modal-title"
              x-init="$el.closest('dialog')?.setAttribute('data-title', <?= json_encode($title) ?>)"><?= $title ?></span>

        <div class=" text-left" x-data="{
            filter: <?= $filterJson ?>,
            advancedOpen: false,
            labels: <?= $labelsJson ?>,
            baseUrl: <?= $baseUrlJson ?>,
            token: <?= $tokenJson ?>,
            copiedWebcal: false,
            copiedFeed: false,
            copiedQuick: false,
            get feedUrl() {
                return this.baseUrl + '?token=' + this.token + (this.filter !== 'all' ? '&filter=' + this.filter : '');
            },
            get webcalUrl() {
                return this.feedUrl.replace(/^https?:\/\//, 'webcal://');
            },
            isFilter(v) { return this.filter === v },
            setFilter(v) { this.filter = v }
        }" @calendar-filter-changed.window="filter = $event.detail.filter"
             hx-get="<?= Router::url('calendar_subscribe_popover', ['partial' => 1]) ?>"
             hx-trigger="calendar-token-rotated from:body"
             x-bind:hx-vals="JSON.stringify({ filter: filter })"
             hx-target="#config-modal-body"
             hx-swap="innerHTML">
            <div class="flex items-start gap-4">
                <div class="flex size-12 shrink-0 items-center justify-center rounded-lg bg-brand/5 text-brand dark:bg-brand/10">
                    <span class="[&_svg]:size-6"><?= $iconCalendar ?></span>
                </div>

                <div>
                    <p class="text-sm leading-6 text-secondary/70">
                        <?= $desc ?>
                    </p>
                </div>
            </div>

            <div class="mt-6 ml-16">
                <label class="text-sm font-medium text-secondary dark:text-secondary/80"><?= $filterLabel ?></label>
                <div class="mt-2 flex flex-wrap gap-2">
                    <?= FilterPills::render(array_keys($labels), [
                            'labels_map' => $labels,
                            'include_all' => false,
                    ]) ?>
                </div>
            </div>

            <div class="mt-6 rounded-2xl border border-brand/10 bg-brand/5 p-4 dark:bg-brand/10 dark:border-brand/20">
                <div class="flex items-start gap-6">
                    <div class="mt-0.5 text-brand">
                        <?= Base::SVG_SPARKLES; ?>
                    </div>
                    <div class="min-w-0 flex-1">
                        <h3 class="font-medium text-primary dark:text-white"><?= $quickSetupTitle ?></h3>
                        <p class="mt-1 text-sm text-secondary/70 dark:text-secondary">
                            <?= $quickSetupDesc ?>
                        </p>

                        <div class="mt-4 flex flex-wrap items-center gap-3">
                            <?= Button::render($openAppLabel, [
                                    'as' => 'a',
                                    'href' => '#',
                                    'attrs' => [':href' => 'webcalUrl'],
                                    'variant' => 'primary',
                                    'size' => 'md',
                            ]) ?>
                            <?= $badgeFilter ?>
                        </div>
                        <p class="mt-6 text-sm text-secondary/70 dark:text-secondary">
                            <?= $quickSetupSub ?>
                        </p>
                    </div>
                </div>
            </div>

            <div class="mt-5">
                <button type="button" @click="advancedOpen = !advancedOpen"
                        class="flex w-full cursor-pointer items-center justify-between  px-1 py-2 text-sm font-medium text-secondary/70 hover:text-primary dark:text-secondary/80 dark:hover:text-white transition-colors focus:outline-none">
                    <?= $advancedSettingsLabel ?>
                    <span class="transition-transform"
                          :class="{ 'rotate-180': advancedOpen }"><?= Base::SVG_CHEVRON_DOWN; ?></span>
                </button>

                <div x-show="advancedOpen" x-collapse.duration.220ms x-cloak class="space-y-4">
                    <div class="mt-3 space-y-4 rounded-2xl border border-divider bg-white p-4 dark:bg-white/5 dark:border-white/10">
                        <div>
                            <div class="flex items-center">
                                <label class="text-xs text-secondary/70"><?= $webcalLabel ?></label>
                                <?= $badgeFilter ?>
                            </div>
                            <div class="mt-2">
                                <?= Input::render('webcal_url', '', '', [
                                        'no_label' => true,
                                        'is_readonly' => true,
                                        'is_copyable' => true,

                                        'input_attrs' => ':value="webcalUrl"',
                                        'size' => 'md'
                                ]) ?>
                            </div>
                        </div>

                        <div>
                            <div class="flex items-center">
                                <label class="text-xs text-secondary/70"><?= $httpsLabel ?></label>
                                <?= $badgeFilter ?>
                            </div>
                            <div class="mt-2">
                                <?= Input::render('feed_url', '', '', [
                                        'no_label' => true,
                                        'is_readonly' => true,
                                        'is_copyable' => true,
                                        'input_attrs' => ':value="feedUrl"',
                                        'size' => 'md'
                                ]) ?>
                            </div>
                        </div>
                    </div>

                    <div class="rounded-2xl border border-danger/10 bg-danger/5 p-4 dark:bg-danger/10 dark:border-danger/20">
                        <div class="flex items-start gap-6">
                            <div class="mt-0.5 text-danger/70">
                                <?= Base::SVG_KEY; ?>
                            </div>
                            <div class="min-w-0 flex-1 space-y-3">
                                <h3 class="font-medium text-danger/70"><?= $securityTitle ?></h3>
                                <p class="text-sm leading-6 text-danger/70">
                                    <?= $securityDesc ?>
                                </p>
                                <?= Button::render($securityRenewLabel, [
                                        'variant' => 'danger',
                                        'size' => 'sm',
                                        'attrs' => [
                                                'command' => 'show-modal',
                                                'commandfor' => 'confirm-modal',
                                                'data-title' => $rotateConfirm,
                                                'data-type' => 'alert',
                                                'hx-get' => Router::url('calendar_rotate_token_confirm', ['partial' => 1]),
                                                'x-bind:hx-vals' => 'JSON.stringify({ filter: filter })',
                                                'hx-target' => '#confirm-modal-body',
                                                'hx-swap' => 'innerHTML',
                                        ]
                                ]) ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <template x-teleport="#config-modal-footer">
                <div class="flex items-center justify-end gap-3 w-full">
                    <?= Button::render($closeLabel, [
                            'variant' => 'ghost',
                            'size' => 'md',
                            'attrs' => [
                                    'command' => 'close',
                                    'commandfor' => 'config-modal'
                            ]
                    ]) ?>
                </div>
            </template>
        </div>
        <?php
        return ob_get_clean();
    }
}
