"use client"

import { useEffect, useRef, useState } from "react"
import { Icon } from "@iconify/react"
import { LandingReveal } from "@/components/landing/landing-reveal"
import {
  LANDING_DEMO_TAB_STYLES,
  landingAppGlowVars,
} from "@/components/landing/landing-data"
import { ULTICAL_APP_NAME, ULTICARDS_APP_NAME } from "@/lib/suite/page-metadata"
import { cn } from "@/lib/utils"

type DemoTab = {
  id: string
  label: string
  icon: string
  src: string
  fakeUrl: string
  hint: string
}

const DEMO_TABS: DemoTab[] = [
  {
    id: "mail",
    label: "Boîte mail",
    icon: "mdi:email-outline",
    src: "/demo/mail",
    fakeUrl: "suite.votre-domaine.fr/mail",
    hint: "Lisez, archivez, répondez, composez — comme dans la vraie boîte.",
  },
  {
    id: "drive",
    label: "UltiDrive",
    icon: "mdi:folder-outline",
    src: "/demo/drive",
    fakeUrl: "suite.votre-domaine.fr/drive",
    hint: "Parcourez, classez, favorisez et recherchez vos fichiers.",
  },
  {
    id: "agenda",
    label: ULTICAL_APP_NAME,
    icon: "mdi:calendar-outline",
    src: "/demo/agenda",
    fakeUrl: "suite.votre-domaine.fr/agenda",
    hint: "Créez des événements, invitez des participants, ajoutez une visio.",
  },
  {
    id: "contacts",
    label: ULTICARDS_APP_NAME,
    icon: "mdi:account-group-outline",
    src: "/demo/contacts",
    fakeUrl: "suite.votre-domaine.fr/contacts",
    hint: "Recherchez, créez et modifiez vos contacts.",
  },
  {
    id: "docs",
    label: "Éditeur UltiDocs",
    icon: "mdi:file-document-edit-outline",
    src: "/demo/docs",
    fakeUrl: "suite.votre-domaine.fr/docs",
    hint: "Le vrai éditeur de la suite : mise en forme, tableaux, styles, pages.",
  },
]

type LandingDemoSectionProps = {
  activeTab?: string
  onActiveTabChange?: (tabId: string) => void
  /** Incrémenté depuis le hero pour forcer le montage des iframes avant scroll. */
  revealNonce?: number
}

export function LandingDemoSection({
  activeTab: controlledTab,
  onActiveTabChange,
  revealNonce = 0,
}: LandingDemoSectionProps = {}) {
  const sectionRef = useRef<HTMLElement>(null)
  const [visible, setVisible] = useState(false)
  const [internalTab, setInternalTab] = useState(DEMO_TABS[0].id)
  const activeTab = controlledTab ?? internalTab
  const setActiveTab = (tabId: string) => {
    if (onActiveTabChange) onActiveTabChange(tabId)
    else setInternalTab(tabId)
  }
  /** Onglets dont l'iframe a été montée (état conservé au changement d'onglet). */
  const [mounted, setMounted] = useState<Record<string, boolean>>({})
  /** Incrément par onglet pour réinitialiser la démo (remount iframe). */
  const [resetKeys, setResetKeys] = useState<Record<string, number>>({})

  useEffect(() => {
    const node = sectionRef.current
    if (!node || visible) return
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          setVisible(true)
          observer.disconnect()
        }
      },
      { rootMargin: "240px 0px" }
    )
    observer.observe(node)
    return () => observer.disconnect()
  }, [visible])

  useEffect(() => {
    if (!revealNonce) return
    setVisible(true)
    setMounted((prev) => ({ ...prev, [activeTab]: true }))
  }, [revealNonce, activeTab])

  useEffect(() => {
    if (!visible) return
    setMounted((prev) => (prev[activeTab] ? prev : { ...prev, [activeTab]: true }))
  }, [visible, activeTab])

  const active = DEMO_TABS.find((tab) => tab.id === activeTab) ?? DEMO_TABS[0]

  return (
    <section id="demo" ref={sectionRef} className="scroll-mt-20 px-4 py-20 sm:px-6">
      <div className="mx-auto flex w-full max-w-6xl flex-col gap-10">
        <LandingReveal className="mx-auto flex max-w-2xl flex-col items-center gap-4 text-center">
          <span className="rounded-full bg-[var(--landing-chip)] px-3.5 py-1 text-xs font-semibold uppercase tracking-wider text-[var(--landing-chip-fg)]">
            Démo interactive
          </span>
          <h2 className="text-balance text-3xl font-bold tracking-tight sm:text-4xl">
            Essayez <span className="landing-gradient-text">maintenant</span>,
            sans compte
          </h2>
          <p className="text-balance text-base leading-relaxed text-[var(--landing-muted)]">
            De vraies fenêtres, de vrais comportements. Tout reste dans votre
            onglet : <strong className="font-semibold text-[var(--landing-fg)]">zéro rétention</strong>,
            rien n'est envoyé ni enregistré.
          </p>
        </LandingReveal>

        <LandingReveal delay={0.1} className="flex flex-col gap-4">
          {/* Onglets */}
          <div className="flex flex-wrap items-center justify-center gap-2">
            {DEMO_TABS.map((tab) => {
              const selected = tab.id === activeTab
              const tabStyle = LANDING_DEMO_TAB_STYLES[tab.id]
              return (
                <button
                  key={tab.id}
                  type="button"
                  onClick={() => setActiveTab(tab.id)}
                  className={cn(
                    "landing-cta h-10 px-5 text-sm",
                    selected ? "landing-cta--primary" : "landing-cta--ghost"
                  )}
                  style={
                    selected && tabStyle
                      ? ({
                          ...landingAppGlowVars(tabStyle.gradient),
                          ...(tabStyle.primaryTextDark ? { color: "#1a1a1a" } : {}),
                        } as React.CSSProperties)
                      : undefined
                  }
                  aria-pressed={selected}
                >
                  <Icon icon={tab.icon} className="size-4.5" aria-hidden />
                  {tab.label}
                </button>
              )
            })}
          </div>

          {/* Fenêtre virtuelle */}
          <div className="landing-glass-strong overflow-hidden rounded-2xl shadow-[0_40px_90px_-40px_rgba(30,40,90,0.5)]">
            <div className="flex items-center gap-1.5 px-3 py-2.5">
              <span className="size-2.5 rounded-full bg-[#ff5f57]" aria-hidden />
              <span className="size-2.5 rounded-full bg-[#febc2e]" aria-hidden />
              <span className="size-2.5 rounded-full bg-[#28c840]" aria-hidden />
              <div className="ml-3 flex h-7 min-w-0 flex-1 items-center gap-2 rounded-full bg-[var(--landing-chip)] px-3 text-xs text-[var(--landing-muted)]">
                <Icon icon="mdi:lock-outline" className="size-3.5 shrink-0" aria-hidden />
                <span className="truncate">{active.fakeUrl}</span>
              </div>
              <button
                type="button"
                onClick={() =>
                  setResetKeys((prev) => ({
                    ...prev,
                    [active.id]: (prev[active.id] ?? 0) + 1,
                  }))
                }
                className="ml-2 flex h-7 items-center gap-1.5 rounded-full px-2.5 text-xs font-medium text-[var(--landing-muted)] transition-colors hover:bg-[var(--landing-chip)] hover:text-[var(--landing-fg)]"
                title="Réinitialiser la démo (tout est éphémère)"
              >
                <Icon icon="mdi:restore" className="size-4" aria-hidden />
                <span className="hidden sm:inline">Réinitialiser</span>
              </button>
              <a
                href={active.src}
                target="_blank"
                rel="noopener noreferrer"
                className="flex h-7 items-center gap-1.5 rounded-full px-2.5 text-xs font-medium text-[var(--landing-muted)] transition-colors hover:bg-[var(--landing-chip)] hover:text-[var(--landing-fg)]"
                title="Ouvrir la démo en plein écran"
              >
                <Icon icon="mdi:open-in-new" className="size-4" aria-hidden />
                <span className="hidden sm:inline">Plein écran</span>
              </a>
            </div>

            <div className="relative h-[30rem] border-t border-[var(--landing-line)] bg-[var(--landing-bg)] sm:h-[34rem] lg:h-[38rem]">
              {DEMO_TABS.map((tab) =>
                mounted[tab.id] ? (
                  <iframe
                    key={`${tab.id}-${resetKeys[tab.id] ?? 0}`}
                    src={tab.src}
                    title={`Démo ${tab.label}`}
                    loading="lazy"
                    className={cn(
                      "absolute inset-0 h-full w-full",
                      tab.id === activeTab ? "block" : "hidden"
                    )}
                  />
                ) : null
              )}
              {!mounted[active.id] ? (
                <div className="absolute inset-0 flex items-center justify-center text-sm text-[var(--landing-muted)]">
                  Chargement de la démo…
                </div>
              ) : null}
            </div>
          </div>

          <p className="flex flex-wrap items-center justify-center gap-2 text-center text-sm text-[var(--landing-muted)]">
            <Icon icon="mdi:incognito" className="size-4.5 shrink-0" aria-hidden />
            {active.hint} Rechargez la page : tout disparaît.
          </p>
        </LandingReveal>
      </div>
    </section>
  )
}
