'use client';

/**
 * PageOrganizerModules - section 13 of /design-system.
 *
 * Demonstrates the 5 day-one deal-row page-organizer modules, each rendering
 * with mock DealCardDeal data and its ConfigEditor in default state.
 * Anchors: #module-deal-row-near-you … #module-deal-row-auto-scroll
 */

import { useState } from 'react';
import { useT } from '@/lib/i18n/react';
import { SectionShell } from '../../components/SectionShell';
import { SAMPLE_DEAL, SAMPLE_DEAL_GROUP, SAMPLE_VENDOR_DEAL } from '../../sample-data';
import type { VendorCardData } from '@/components/ui/domain/VendorCard';
import { CLIENT_MODULE_REGISTRY } from '@/server/page-layout/client-registry';

const MOCK_DEALS = [SAMPLE_DEAL, SAMPLE_VENDOR_DEAL, SAMPLE_DEAL_GROUP];

// Use an inline data-URI placeholder that doesn't hit external URLs in the design-system gallery.
const PLACEHOLDER_IMG =
  'data:image/svg+xml,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 width%3D%221920%22 height%3D%221080%22%3E%3Crect fill%3D%22%23c7d2fe%22 width%3D%22100%25%22 height%3D%22100%25%22%2F%3E%3C%2Fsvg%3E';

const MOCK_BANNER_CONFIG = {
  imageUrl: PLACEHOLDER_IMG,
  alt: { he: 'פרסומת לדוגמה', en: 'Sample banner' },
  href: '#',
  aspect: '16:9' as const,
  mode: 'featured' as const,
};

const MOCK_VENDOR: VendorCardData = {
  id: 'sample-vendor-1',
  businessName: 'מסעדת רוטשילד 22',
  displayName: 'רוטשילד 22',
  logoUrl: null,
  heroImageUrl: PLACEHOLDER_IMG,
  reviewsScore: '4.70',
  reviewsCount: 38,
  city: 'תל אביב',
  lat: '32.0614',
  lng: '34.7761',
  businessTypeNames: ['מסעדה'],
  activeDealsCount: 2,
  activeDealsTypes: ['COUPON'],
  todayHours: '12:00-23:00',
};

const MOCK_VENDORS = [
  MOCK_VENDOR,
  {
    ...MOCK_VENDOR,
    id: 'sample-vendor-2',
    businessName: 'ספא שיין',
    displayName: 'שיין',
    city: 'הרצליה',
    category: ['dessert'],
    activeDealsCount: 1,
    activeDealsTypes: ['GROUP'],
  },
];

const MOCK_PAGE_HERO_CONFIG_NO_BG = {
  title: { he: 'ברוכים הבאים למולטידיל', en: 'Welcome to Multideal' },
  subtitle: { he: 'מצאו את הדילים הטובים ביותר באזורכם', en: 'Find the best deals near you' },
};

const MOCK_PAGE_HERO_CONFIG_WITH_BG = {
  title: { he: 'הצעות מיוחדות לסוף שבוע', en: 'Weekend Special Offers' },
  subtitle: {
    he: 'דילים מוזלים על מסעדות ובתי קפה',
    en: 'Discounted deals on restaurants and cafés',
  },
  bgImage: PLACEHOLDER_IMG,
};

const MOCK_RICH_TEXT_CONFIG = {
  body: {
    he: '<h2>אודות מולטידיל</h2><p>מולטידיל היא הפלטפורמה המובילה לדילים מקומיים בישראל. אנחנו מחברים עסקים מקומיים עם לקוחות באמצעות הצעות שקופות ומדויקות.</p><ul><li>דילים יומיים</li><li>חוויות ייחודיות</li><li>מוצרים מקומיים</li></ul>',
    en: '<h2>About Multideal</h2><p>Multideal is the leading local deals platform in Israel. We connect local businesses with customers through transparent, specific offers.</p><ul><li>Daily deals</li><li>Unique experiences</li><li>Local products</li></ul>',
  },
};

const MOCK_STATIC_CONFIG = {
  body: {
    he: 'ברוכים הבאים למולטידיל!\n\nמצאו את הדילים הטובים ביותר באזורכם.',
    en: 'Welcome to Multideal!\n\nFind the best deals in your area.',
  },
  background: 'neutral' as const,
};

/** Renders one module entry: the live Component preview + its ConfigEditor. */
function ModuleEntry<TConfig>({
  id,
  def,
  data,
}: {
  id: string;
  def: {
    type: string;
    defaultConfig: TConfig;
    Component: React.FC<{ config: TConfig; data: unknown; demo?: boolean }>;
    ConfigEditor: React.FC<{ config: TConfig; onChange: (c: TConfig) => void }>;
  };
  data: unknown;
}) {
  const [config, setConfig] = useState<TConfig>(def.defaultConfig);
  // Editors may fetch live admin data on mount — mount only once the <details> is opened.
  const [editorOpen, setEditorOpen] = useState(false);

  return (
    <div id={id} className="border-border-default flex flex-col gap-4 rounded-lg border p-4">
      <div className="flex flex-col gap-1">
        <code className="text-brand-primary-700 text-sm">{def.type}</code>
      </div>

      {/* Live component preview */}
      <div className="bg-surface-base border-border-subtle overflow-hidden rounded-md border">
        <def.Component config={config} data={data} demo />
      </div>

      {/* Config editor */}
      <details
        className="group"
        onToggle={(e) => setEditorOpen((e.currentTarget as HTMLDetailsElement).open)}
      >
        <summary className="cursor-pointer list-none">
          <span className="text-text-secondary text-sm font-medium underline-offset-2 hover:underline">
            ConfigEditor
          </span>
        </summary>
        <div className="mt-3 max-w-xs">
          {editorOpen && <def.ConfigEditor config={config} onChange={setConfig} />}
        </div>
      </details>
    </div>
  );
}

export function PageOrganizerModules() {
  const t = useT('design_system');

  function mod(type: string): (typeof CLIENT_MODULE_REGISTRY)[string] {
    const definition = CLIENT_MODULE_REGISTRY[type];
    if (!definition) throw new Error(`Unknown client module: ${type}`);
    return definition;
  }

  return (
    <SectionShell
      id="modules"
      title={t('sidebar_modules')}
      description={t('modules_section_intro')}
    >
      <ModuleEntry id="module-deal-row-near-you" def={mod('deal-row:near-you')} data={MOCK_DEALS} />
      <ModuleEntry
        id="module-deal-row-hot-deals"
        def={mod('deal-row:hot-deals')}
        data={MOCK_DEALS}
      />
      <ModuleEntry
        id="module-deal-row-group-deals"
        def={mod('deal-row:group-deals')}
        data={MOCK_DEALS}
      />
      <ModuleEntry
        id="module-deal-row-whats-left"
        def={mod('deal-row:whats-left')}
        data={MOCK_DEALS}
      />
      <ModuleEntry
        id="module-deal-row-auto-scroll"
        def={mod('deal-row:auto-scroll')}
        data={MOCK_DEALS}
      />
      <ModuleEntry id="module-deal-row-for-you" def={mod('deal-row:for-you')} data={MOCK_DEALS} />
      <ModuleEntry
        id="module-deal-row-category"
        def={mod('deal-row:category')}
        data={{ deals: MOCK_DEALS, categorySlug: 'meal' }}
      />
      <ModuleEntry
        id="module-deal-row-custom-query"
        def={mod('deal-row:custom-query')}
        data={MOCK_DEALS}
      />
      <ModuleEntry
        id="module-banner"
        def={{ ...mod('banner'), defaultConfig: MOCK_BANNER_CONFIG }}
        data={null}
      />
      <ModuleEntry id="module-vendor-spotlight" def={mod('vendor-spotlight')} data={MOCK_VENDORS} />
      <ModuleEntry
        id="module-static-content"
        def={{ ...mod('static-content'), defaultConfig: MOCK_STATIC_CONFIG }}
        data={null}
      />
      {/* Variant A: brand-color background (no bgImage) */}
      <ModuleEntry
        id="module-page-hero"
        def={{ ...mod('page-hero'), defaultConfig: MOCK_PAGE_HERO_CONFIG_NO_BG }}
        data={null}
      />
      {/* Variant B: background image */}
      <ModuleEntry
        id="module-page-hero-bg"
        def={{ ...mod('page-hero'), defaultConfig: MOCK_PAGE_HERO_CONFIG_WITH_BG }}
        data={null}
      />
      <ModuleEntry
        id="module-rich-text-content"
        def={{ ...mod('rich-text-content'), defaultConfig: MOCK_RICH_TEXT_CONFIG }}
        data={null}
      />
    </SectionShell>
  );
}
