"use client";

/**
 * Live Conference Intelligence Hub — attendee experience.
 * Component map: ConferenceHeader, LiveVideoPlayer (+LiveStatus states), CurrentSession,
 * DiscussionPanel (NOW DISCUSSING), LiveTimeline, KnowledgePanel (KeyTakeaways /
 * ImportantQuotes / stats / ConferenceResources), SocialPulse, HashtagBar,
 * UpcomingSessions, LiveQA, AskConferenceAI (placeholder), MyNotes.
 * All content is API-driven via /api/live/[id]/feed polling (5s) — no page refresh needed.
 */

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import type { LiveFeed, LiveFeedUpdate, LiveSessionInfo } from "@/lib/live";
import { LIVE_UPDATE_TYPE_META } from "@/lib/constants";
import { addNoteAction, followSessionAction, removeNoteAction, submitQuestionAction } from "@/app/live/[slug]/actions";

type Note = { id: string; text: string | null; title: string | null; at: string };

const fmtT = (iso: string) =>
  new Date(iso).toLocaleTimeString("en-IN", { hour: "numeric", minute: "2-digit", hour12: true, timeZone: "Asia/Kolkata" });

function useCountdown(targetIso: string) {
  const [left, setLeft] = useState(() => new Date(targetIso).getTime() - Date.now());
  useEffect(() => {
    const t = setInterval(() => setLeft(new Date(targetIso).getTime() - Date.now()), 1000);
    return () => clearInterval(t);
  }, [targetIso]);
  if (left <= 0) return null;
  const h = Math.floor(left / 3600000), m = Math.floor((left % 3600000) / 60000), s = Math.floor((left % 60000) / 1000);
  return h > 0 ? `${h}h ${String(m).padStart(2, "0")}m` : `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}

const glass = "rounded-2xl border border-white/10 bg-white/[0.06] backdrop-blur-xl";
const chip = "inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold";

export function LiveScreen({ initialFeed, userName, initialNotes }: { initialFeed: LiveFeed; userName: string; initialNotes: Note[] }) {
  const [feed, setFeed] = useState(initialFeed);
  const [notes, setNotes] = useState<Note[]>(initialNotes);
  const [activeTag, setActiveTag] = useState<string | null>(null);
  const [aiOpen, setAiOpen] = useState(false);
  const [notesOpen, setNotesOpen] = useState(false);
  const [toast, setToast] = useState<string | null>(null);
  const knownIds = useRef(new Set(initialFeed.updates.map((u) => u.id)));
  const [freshIds, setFreshIds] = useState<Set<string>>(new Set());
  const conf = feed.conference;

  // ── realtime: poll the feed; highlight anything new ──
  useEffect(() => {
    const t = setInterval(async () => {
      try {
        const res = await fetch(`/api/live/${conf.id}/feed`, { cache: "no-store" });
        if (!res.ok) return;
        const next: LiveFeed = await res.json();
        const fresh = next.updates.filter((u) => !knownIds.current.has(u.id)).map((u) => u.id);
        fresh.forEach((id) => knownIds.current.add(id));
        if (fresh.length) {
          setFreshIds(new Set(fresh));
          setTimeout(() => setFreshIds(new Set()), 4000);
        }
        setFeed(next);
      } catch { /* offline blip — keep the last good feed */ }
    }, 5000);
    return () => clearInterval(t);
  }, [conf.id]);

  const say = (msg: string) => { setToast(msg); setTimeout(() => setToast(null), 2500); };

  const saveNote = useCallback(async (update: LiveFeedUpdate) => {
    const res = await addNoteAction(conf.id, update.id, null);
    if (res.ok && res.note) { setNotes((n) => [res.note!, ...n]); say("Added to My Notes"); }
  }, [conf.id]);

  const isLive = conf.status === "LIVE";
  const isEnded = conf.status === "COMPLETED" || conf.status === "ARCHIVED";
  const showVideo = conf.type !== "PHYSICAL";
  const updates = activeTag ? feed.updates.filter((u) => u.tags.includes(activeTag)) : feed.updates;
  const nowDiscussing = feed.updates.filter((u) => ["TOPIC", "KEY_POINT"].includes(u.type)).slice(0, 6);
  const takeaways = feed.updates.filter((u) => u.type === "KEY_POINT").slice(0, 6);
  const quotes = feed.updates.filter((u) => u.type === "QUOTE").slice(0, 3);
  const stats = feed.updates.filter((u) => u.type === "STATISTIC").slice(0, 4);
  const resources = feed.updates.filter((u) => u.type === "RESOURCE").slice(0, 6);

  return (
    <div className="min-h-screen bg-[#0b0d14] text-slate-100" style={{ colorScheme: "dark" }}>
      <ConferenceHeader feed={feed} onNotes={() => setNotesOpen(true)} noteCount={notes.length} />
      <HashtagBar hashtags={conf.hashtags} activeTag={activeTag} onPick={setActiveTag} />

      <main className="mx-auto max-w-[1600px] px-4 pb-24 pt-4">
        {/* Row 1: video + now discussing */}
        <div className={`grid gap-4 ${showVideo ? "xl:grid-cols-[1fr_380px]" : ""}`}>
          {showVideo && <LiveVideoPlayer feed={feed} />}
          <DiscussionPanel items={nowDiscussing} freshIds={freshIds} onSave={saveNote} full={!showVideo} />
        </div>

        {/* Row 2: session strip */}
        <div className="mt-4 grid gap-4 md:grid-cols-2">
          <CurrentSession session={feed.currentSession} accent={conf.primaryColor} onFollow={async (id) => { await followSessionAction(id); say("Following session — see My Schedule"); }} />
          <UpcomingSessions next={feed.nextSession} slug={conf.slug} />
        </div>

        {/* Row 3: timeline */}
        <LiveTimeline updates={updates} freshIds={freshIds} onSave={saveNote} activeTag={activeTag} onPickTag={setActiveTag} />

        {/* Row 4: knowledge + social */}
        <div className="mt-4 grid gap-4 xl:grid-cols-[1fr_380px]">
          <KnowledgePanel takeaways={takeaways} quotes={quotes} stats={stats} resources={resources} ended={isEnded} />
          <SocialPulse hashtags={conf.hashtags} activeTag={activeTag} />
        </div>

        <LiveQA confId={conf.id} questions={feed.questions} />
      </main>

      {/* Floating: Ask AI + toast */}
      <button
        onClick={() => setAiOpen(true)}
        className="fx-shine fixed bottom-5 right-5 z-40 rounded-2xl bg-gradient-to-r from-indigo-500 via-violet-500 to-fuchsia-500 px-5 py-3 text-sm font-bold text-white shadow-2xl shadow-indigo-500/40 transition hover:brightness-110"
      >
        ✨ Ask Conference AI
      </button>
      {toast && (
        <div className="fx-pop-in fixed bottom-5 left-1/2 z-50 -translate-x-1/2 rounded-xl border border-emerald-500/30 bg-emerald-950/90 px-4 py-2.5 text-sm font-semibold text-emerald-300 shadow-xl backdrop-blur">
          ✓ {toast}
        </div>
      )}
      {aiOpen && <AskConferenceAI onClose={() => setAiOpen(false)} confName={conf.name} />}
      {notesOpen && <MyNotes notes={notes} onClose={() => setNotesOpen(false)} onRemove={async (id) => { await removeNoteAction(id); setNotes((n) => n.filter((x) => x.id !== id)); }} confId={conf.id} onAdd={async (text) => { const r = await addNoteAction(conf.id, null, text); if (r.ok && r.note) setNotes((n) => [r.note!, ...n]); }} />}
      <div className="pb-safe" />
      <footer className="border-t border-white/5 py-4 text-center text-xs text-slate-600">
        {userName} · Live Conference Intelligence Hub · <Link href="/me" className="hover:text-slate-400">Exit to My Conferences</Link>
      </footer>
    </div>
  );
}

// ── Header ────────────────────────────────────────────────

function ConferenceHeader({ feed, onNotes, noteCount }: { feed: LiveFeed; onNotes: () => void; noteCount: number }) {
  const conf = feed.conference;
  const isLive = conf.status === "LIVE";
  return (
    <header className="sticky top-0 z-30 border-b border-white/10 bg-[#0b0d14]/85 backdrop-blur-xl">
      <div className="mx-auto flex h-14 max-w-[1600px] items-center justify-between gap-3 px-4">
        <div className="flex min-w-0 items-center gap-3">
          <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-sm font-bold text-white" style={{ background: conf.primaryColor }}>
            {conf.name[0]}
          </span>
          <div className="min-w-0">
            <div className="flex items-center gap-2">
              <LiveStatusBadge status={conf.status} />
              <span className="truncate text-sm font-bold">{conf.name}</span>
            </div>
            <div className="hidden truncate text-[11px] text-slate-500 sm:block">
              {feed.currentSession ? `Session: ${feed.currentSession.title}` : "No session in progress"}
              {" · "}{fmtT(feed.serverTime)} · {feed.counts.attending.toLocaleString("en-IN")} attending
              {isLive && feed.counts.checkedIn > 0 && ` · ${feed.counts.checkedIn} on-site`}
            </div>
          </div>
        </div>
        <div className="flex shrink-0 items-center gap-2">
          <button onClick={onNotes} className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs font-semibold text-slate-300 transition hover:bg-white/10">
            📝 My Notes{noteCount > 0 && <span className="ml-1.5 rounded-full bg-indigo-500 px-1.5 text-[10px] text-white">{noteCount}</span>}
          </button>
          <Link href="/me" className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs font-semibold text-slate-300 transition hover:bg-white/10">
            Exit ↩
          </Link>
        </div>
      </div>
    </header>
  );
}

function LiveStatusBadge({ status }: { status: string }) {
  if (status === "LIVE")
    return (
      <span className={`${chip} bg-emerald-500/15 text-emerald-400`}>
        <span className="fx-live-dot mr-1.5 h-1.5 w-1.5 rounded-full bg-emerald-400" /> LIVE
      </span>
    );
  if (status === "COMPLETED" || status === "ARCHIVED") return <span className={`${chip} bg-violet-500/15 text-violet-300`}>ENDED</span>;
  return <span className={`${chip} bg-amber-500/15 text-amber-300`}>STARTING SOON</span>;
}

// ── Hashtag bar ───────────────────────────────────────────

function HashtagBar({ hashtags, activeTag, onPick }: { hashtags: string[]; activeTag: string | null; onPick: (t: string | null) => void }) {
  if (hashtags.length === 0) return null;
  return (
    <div className="mx-auto flex max-w-[1600px] flex-wrap items-center gap-2 px-4 pt-3">
      {hashtags.map((h) => (
        <button
          key={h}
          onClick={() => onPick(activeTag === h ? null : h)}
          className={`rounded-full px-3 py-1 text-xs font-semibold transition ${
            activeTag === h ? "bg-indigo-500 text-white" : "border border-white/10 bg-white/5 text-indigo-300 hover:bg-white/10"
          }`}
        >
          {h.startsWith("#") ? h : `#${h}`}
        </button>
      ))}
      {activeTag && <button onClick={() => onPick(null)} className="text-xs text-slate-500 hover:text-slate-300">clear filter ✕</button>}
    </div>
  );
}

// ── Video ─────────────────────────────────────────────────

function LiveVideoPlayer({ feed }: { feed: LiveFeed }) {
  const conf = feed.conference;
  const countdown = useCountdown(conf.startAt);
  const isLive = conf.status === "LIVE";
  const isEnded = conf.status === "COMPLETED" || conf.status === "ARCHIVED";

  return (
    <div className={`${glass} overflow-hidden`}>
      <div className="relative aspect-video w-full bg-black">
        {isLive && conf.embedUrl ? (
          <iframe
            src={conf.embedUrl}
            title="Live stream"
            className="absolute inset-0 h-full w-full"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen"
            allowFullScreen
          />
        ) : (
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-gradient-to-br from-slate-900 to-black text-center">
            {isEnded ? (
              <>
                <div className="text-4xl">🎬</div>
                <div className="text-lg font-bold">Conference stream has ended</div>
                <div className="max-w-sm text-sm text-slate-500">The knowledge below — takeaways, quotes, resources and the full timeline — remains available as this conference's record.</div>
                {conf.streamUrl && (
                  <a href={conf.streamUrl} target="_blank" rel="noreferrer" className="mt-1 rounded-lg bg-white/10 px-4 py-2 text-sm font-semibold hover:bg-white/20">▶ Watch recording</a>
                )}
              </>
            ) : isLive && !conf.embedUrl ? (
              <>
                <div className="fx-live-dot h-3 w-3 rounded-full bg-emerald-400" />
                <div className="text-lg font-bold">Waiting for live stream…</div>
                <div className="text-sm text-slate-500">The organizers haven't connected a stream URL yet. Updates below are live.</div>
              </>
            ) : (
              <>
                <div className="text-4xl">⏳</div>
                <div className="text-lg font-bold">Starting soon</div>
                {countdown ? (
                  <div className="font-mono text-3xl font-black tracking-widest text-amber-300">{countdown}</div>
                ) : (
                  <div className="text-sm text-slate-500">Any moment now — hold tight.</div>
                )}
              </>
            )}
          </div>
        )}
        {isLive && conf.embedUrl && (
          <span className={`${chip} absolute left-3 top-3 z-10 bg-red-600 text-white shadow-lg`}>
            <span className="fx-live-dot mr-1.5 h-1.5 w-1.5 rounded-full bg-white" /> LIVE
          </span>
        )}
      </div>
    </div>
  );
}

// ── NOW DISCUSSING ────────────────────────────────────────

function DiscussionPanel({ items, freshIds, onSave, full }: { items: LiveFeedUpdate[]; freshIds: Set<string>; onSave: (u: LiveFeedUpdate) => void; full: boolean }) {
  return (
    <section className={`${glass} flex max-h-[520px] flex-col p-4 ${full ? "" : ""}`}>
      <h2 className="flex items-center gap-2 text-xs font-black uppercase tracking-[0.2em] text-indigo-300">
        <span className="fx-live-dot h-1.5 w-1.5 rounded-full bg-indigo-400" /> Now discussing
      </h2>
      <div className="mt-3 flex-1 space-y-3 overflow-y-auto pr-1">
        {items.length === 0 && <p className="text-sm text-slate-500">Discussion points will appear here as the organizers publish them.</p>}
        {items.map((u, i) => (
          <div
            key={u.id}
            className={`rounded-xl border p-3 transition ${
              i === 0
                ? "border-indigo-400/40 bg-indigo-500/10 shadow-[0_0_30px_rgba(99,102,241,0.15)]"
                : "border-white/5 bg-white/[0.03]"
            } ${freshIds.has(u.id) ? "fx-pop-in" : ""}`}
          >
            <div className="flex items-center justify-between gap-2 text-[11px] text-slate-500">
              <span className="tabular-nums">{fmtT(u.at)}</span>
              <button onClick={() => onSave(u)} className="rounded-md px-1.5 py-0.5 text-[11px] font-semibold text-indigo-300 opacity-80 transition hover:bg-white/10" title="Add to My Notes">＋ Notes</button>
            </div>
            <div className={`mt-0.5 font-bold ${i === 0 ? "text-base" : "text-sm"}`}>{u.title}</div>
            {u.body && <p className={`mt-1 text-sm leading-relaxed text-slate-400 ${i === 0 ? "" : "line-clamp-2"}`}>{u.body}</p>}
            {u.speaker && <div className="mt-1.5 text-xs font-semibold text-slate-300">🎤 {u.speaker.name}{u.speaker.designation ? ` · ${u.speaker.designation}` : ""}</div>}
          </div>
        ))}
      </div>
    </section>
  );
}

// ── Sessions ──────────────────────────────────────────────

function SpeakerAvatar({ name, photoUrl, size = 36 }: { name: string; photoUrl: string | null; size?: number }) {
  return photoUrl ? (
    // eslint-disable-next-line @next/next/no-img-element
    <img src={photoUrl} alt={name} className="rounded-full object-cover ring-2 ring-white/20" style={{ width: size, height: size }} />
  ) : (
    <span className="flex items-center justify-center rounded-full bg-indigo-500/20 font-bold text-indigo-300 ring-2 ring-white/10" style={{ width: size, height: size, fontSize: size * 0.36 }}>
      {name.split(/\s+/).slice(0, 2).map((w) => w[0]).join("")}
    </span>
  );
}

function CurrentSession({ session, accent, onFollow }: { session: LiveSessionInfo | null; accent: string; onFollow: (id: string) => void }) {
  if (!session)
    return (
      <section className={`${glass} flex items-center justify-center p-5 text-sm text-slate-500`}>
        No session in progress right now — check Up Next.
      </section>
    );
  return (
    <section className={`${glass} p-5`} style={{ boxShadow: `inset 3px 0 0 ${accent}` }}>
      <div className="flex items-center justify-between">
        <h2 className="text-xs font-black uppercase tracking-[0.2em] text-slate-500">Current session</h2>
        <button onClick={() => onFollow(session.id)} className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1 text-[11px] font-semibold text-slate-300 hover:bg-white/10">☆ Follow</button>
      </div>
      <div className="mt-2 text-lg font-bold">{session.title}</div>
      <div className="text-sm tabular-nums text-slate-500">
        {fmtT(session.startAt)} – {fmtT(session.endAt)}{session.room ? ` · ${session.room}` : ""}
      </div>
      {session.abstract && <p className="mt-2 line-clamp-2 text-sm text-slate-400">{session.abstract}</p>}
      <div className="mt-3 flex flex-wrap gap-3">
        {session.speakers.map((s) => (
          <div key={s.name} className="flex items-center gap-2">
            <SpeakerAvatar name={s.name} photoUrl={s.photoUrl} />
            <div className="text-xs">
              <div className="font-bold text-slate-200">{s.name}</div>
              <div className="text-slate-500">{[s.designation, s.organization].filter(Boolean).join(", ")}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function UpcomingSessions({ next, slug }: { next: LiveSessionInfo | null; slug: string }) {
  const countdown = useCountdown(next?.startAt ?? new Date().toISOString());
  return (
    <section className={`${glass} p-5`}>
      <div className="flex items-center justify-between">
        <h2 className="text-xs font-black uppercase tracking-[0.2em] text-slate-500">Up next</h2>
        <Link href={`/c/${slug}/schedule`} target="_blank" className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1 text-[11px] font-semibold text-slate-300 hover:bg-white/10">View agenda ↗</Link>
      </div>
      {next ? (
        <>
          <div className="mt-2 text-lg font-bold">{next.title}</div>
          <div className="text-sm tabular-nums text-slate-500">
            {fmtT(next.startAt)} – {fmtT(next.endAt)}{next.room ? ` · ${next.room}` : ""}
          </div>
          {next.speakers.length > 0 && <div className="mt-1.5 text-xs text-slate-400">🎤 {next.speakers.map((s) => s.name).join(", ")}</div>}
          {countdown && <div className="mt-2 inline-block rounded-lg bg-amber-500/10 px-2.5 py-1 text-xs font-bold text-amber-300">Starts in {countdown}</div>}
        </>
      ) : (
        <p className="mt-3 text-sm text-slate-500">No more sessions scheduled.</p>
      )}
    </section>
  );
}

// ── Timeline ──────────────────────────────────────────────

function LiveTimeline({ updates, freshIds, onSave, activeTag, onPickTag }: { updates: LiveFeedUpdate[]; freshIds: Set<string>; onSave: (u: LiveFeedUpdate) => void; activeTag: string | null; onPickTag: (t: string | null) => void }) {
  const [shown, setShown] = useState(12);
  return (
    <section className={`${glass} mt-4 p-5`}>
      <h2 className="text-xs font-black uppercase tracking-[0.2em] text-slate-500">
        Conference timeline {activeTag && <span className="ml-2 normal-case tracking-normal text-indigo-300">filtered: {activeTag}</span>}
      </h2>
      <div className="relative mt-4 space-y-4 before:absolute before:bottom-2 before:left-[7px] before:top-2 before:w-px before:bg-white/10">
        {updates.length === 0 && <p className="text-sm text-slate-500">The live record of this conference will build here.</p>}
        {updates.slice(0, shown).map((u) => {
          const meta = LIVE_UPDATE_TYPE_META[u.type] ?? LIVE_UPDATE_TYPE_META.KEY_POINT;
          return (
            <div key={u.id} className={`relative pl-7 ${freshIds.has(u.id) ? "fx-pop-in" : ""}`}>
              <span className={`absolute left-0 top-1 flex h-4 w-4 items-center justify-center rounded-full text-[9px] ${u.featured ? "bg-amber-400 text-black" : "bg-white/10"}`}>
                {u.featured ? "★" : "●"}
              </span>
              <div className="flex flex-wrap items-center gap-2 text-[11px] text-slate-500">
                <span className="tabular-nums font-semibold text-slate-400">{fmtT(u.at)}</span>
                <span className={`${chip} ${meta.cls}`}>{meta.icon} {meta.label}</span>
                {u.session && <span className="text-slate-600">· {u.session.title}</span>}
              </div>
              <div className="mt-0.5 font-bold">{u.title}</div>
              {u.quote && <blockquote className="mt-1 border-l-2 border-violet-400/50 pl-3 text-sm italic text-violet-200">“{u.quote}”</blockquote>}
              {u.statValue && (
                <div className="mt-1 flex items-baseline gap-2"><span className="text-2xl font-black text-emerald-300">{u.statValue}</span><span className="text-sm text-slate-400">{u.statLabel}</span></div>
              )}
              {u.body && !u.quote && <p className="mt-1 max-w-3xl text-sm text-slate-400">{u.body}</p>}
              <div className="mt-1.5 flex flex-wrap items-center gap-2 text-[11px]">
                {u.speaker && <span className="font-semibold text-slate-300">🎤 {u.speaker.name}</span>}
                {u.tags.map((t) => (
                  <button key={t} onClick={() => onPickTag(activeTag === t ? null : t)} className={`rounded-full px-2 py-0.5 font-semibold ${activeTag === t ? "bg-indigo-500 text-white" : "bg-white/5 text-indigo-300 hover:bg-white/10"}`}>#{t.replace(/^#/, "")}</button>
                ))}
                {u.link && <a href={u.link} target="_blank" rel="noreferrer" className="font-semibold text-cyan-300 hover:underline">🔗 Open resource</a>}
                <button onClick={() => onSave(u)} className="text-slate-500 hover:text-indigo-300">＋ Add to My Notes</button>
                <button onClick={() => { navigator.clipboard?.writeText(`${u.title} — ${u.quote ?? u.body ?? ""}`.trim()); }} className="text-slate-500 hover:text-slate-300" title="Copy to share">↗ Share</button>
              </div>
            </div>
          );
        })}
      </div>
      {updates.length > shown && (
        <button onClick={() => setShown((n) => n + 12)} className="mt-4 w-full rounded-xl border border-white/10 bg-white/5 py-2 text-sm font-semibold text-slate-300 hover:bg-white/10">
          Show earlier updates ({updates.length - shown} more)
        </button>
      )}
    </section>
  );
}

// ── Knowledge ─────────────────────────────────────────────

function KnowledgePanel({ takeaways, quotes, stats, resources, ended }: { takeaways: LiveFeedUpdate[]; quotes: LiveFeedUpdate[]; stats: LiveFeedUpdate[]; resources: LiveFeedUpdate[]; ended: boolean }) {
  return (
    <section className={`${glass} p-5`}>
      <h2 className="text-xs font-black uppercase tracking-[0.2em] text-slate-500">
        Conference knowledge {ended && <span className="ml-2 normal-case tracking-normal text-violet-300">— final record</span>}
      </h2>
      <div className="mt-4 grid gap-5 md:grid-cols-2">
        <div>
          <h3 className="text-sm font-bold text-amber-300">💡 Key takeaways</h3>
          <ul className="mt-2 space-y-1.5 text-sm text-slate-300">
            {takeaways.length === 0 && <li className="text-slate-600">Takeaways appear as key points are published.</li>}
            {takeaways.map((t) => <li key={t.id} className="flex gap-2"><span className="text-amber-400">•</span>{t.title}</li>)}
          </ul>
          <h3 className="mt-5 text-sm font-bold text-violet-300">❝ Important quotes</h3>
          <div className="mt-2 space-y-2">
            {quotes.length === 0 && <p className="text-sm text-slate-600">Memorable lines will be captured here.</p>}
            {quotes.map((q) => (
              <blockquote key={q.id} className="border-l-2 border-violet-400/50 pl-3 text-sm italic text-violet-100">
                “{q.quote ?? q.title}”{q.speaker && <footer className="mt-0.5 text-xs not-italic text-slate-500">— {q.speaker.name}</footer>}
              </blockquote>
            ))}
          </div>
        </div>
        <div>
          <h3 className="text-sm font-bold text-emerald-300">📊 Key statistics</h3>
          <div className="mt-2 grid grid-cols-2 gap-2">
            {stats.length === 0 && <p className="col-span-2 text-sm text-slate-600">Numbers worth remembering land here.</p>}
            {stats.map((s) => (
              <div key={s.id} className="rounded-xl border border-white/5 bg-white/[0.03] p-3">
                <div className="text-2xl font-black text-emerald-300">{s.statValue ?? "—"}</div>
                <div className="mt-0.5 text-xs text-slate-400">{s.statLabel ?? s.title}</div>
              </div>
            ))}
          </div>
          <h3 className="mt-5 text-sm font-bold text-cyan-300">📎 Resources</h3>
          <ul className="mt-2 space-y-1.5 text-sm">
            {resources.length === 0 && <li className="text-slate-600">Presentations, papers and reports will be linked here.</li>}
            {resources.map((r) => (
              <li key={r.id}>
                {r.link ? (
                  <a href={r.link} target="_blank" rel="noreferrer" className="text-cyan-300 hover:underline">↓ {r.title}</a>
                ) : (
                  <span className="text-slate-300">{r.title}</span>
                )}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

// ── Social pulse (provider-pluggable; demo feed until an X/API provider is configured) ──

function SocialPulse({ hashtags, activeTag }: { hashtags: string[]; activeTag: string | null }) {
  const [refreshedAt, setRefreshedAt] = useState(Date.now());
  const tag = activeTag ?? hashtags[0] ?? "#conference";
  const posts = useMemo(() => {
    const handles = ["@priya_builds", "@ai_bharat_dev", "@conf_junkie", "@meetu_tech", "@delhi_dev"];
    const bodies = [
      `Excited to be attending — the energy at this conference is unreal 🔥 ${tag}`,
      `The point on multilingual AI hit home. This is the decade of Indic tech. ${tag}`,
      `Live notes thread from the keynote 🧵 ${tag}`,
      `Networking lounge is buzzing. Great conversations on DPI at scale. ${tag}`,
      `That statistic on adoption just changed my roadmap. ${tag}`,
    ];
    return bodies.map((b, i) => ({
      id: `${tag}-${i}`,
      handle: handles[i % handles.length],
      body: b,
      mins: 3 + i * 9,
      likes: 45 + ((i * 97) % 380),
      reposts: 8 + ((i * 31) % 90),
    }));
  }, [tag, refreshedAt]);

  return (
    <section className={`${glass} flex flex-col p-5`}>
      <div className="flex items-center justify-between">
        <h2 className="text-xs font-black uppercase tracking-[0.2em] text-slate-500">Social pulse <span className="ml-1 normal-case tracking-normal text-indigo-300">{tag.startsWith("#") ? tag : `#${tag}`}</span></h2>
        <button onClick={() => setRefreshedAt(Date.now())} className="rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-400 hover:bg-white/10">↻ Refresh</button>
      </div>
      <div className="mt-3 flex-1 space-y-2.5 overflow-y-auto">
        {posts.map((p) => (
          <article key={p.id} className="rounded-xl border border-white/5 bg-white/[0.03] p-3">
            <div className="flex items-center justify-between text-[11px] text-slate-500">
              <span className="font-bold text-slate-300">𝕏 {p.handle}</span>
              <span>{p.mins}m ago</span>
            </div>
            <p className="mt-1 text-sm text-slate-300">{p.body}</p>
            <div className="mt-1.5 flex gap-4 text-[11px] text-slate-500">
              <span>❤️ {p.likes}</span><span>🔁 {p.reposts}</span>
              <span className="ml-auto cursor-not-allowed opacity-60" title="Opens on X when a live provider is connected">Open ↗</span>
            </div>
          </article>
        ))}
      </div>
      <p className="mt-3 rounded-lg bg-white/[0.03] px-3 py-2 text-[11px] text-slate-600">
        Demo feed — connect an X/social API provider in System settings to show live posts. If the provider fails, the rest of this screen keeps working.
      </p>
    </section>
  );
}

// ── Q&A ───────────────────────────────────────────────────

function LiveQA({ confId, questions }: { confId: string; questions: { id: string; name: string; question: string; at: string }[] }) {
  const [open, setOpen] = useState(false);
  const [text, setText] = useState("");
  const [state, setState] = useState<"idle" | "sending" | "sent" | "error">("idle");
  return (
    <section className={`${glass} mt-4 p-5`}>
      <button onClick={() => setOpen(!open)} className="flex w-full items-center justify-between text-left">
        <h2 className="text-xs font-black uppercase tracking-[0.2em] text-slate-500">🙋 Live Q&A {questions.length > 0 && <span className="ml-2 text-indigo-300">{questions.length} on screen</span>}</h2>
        <span className="text-slate-500">{open ? "▴" : "▾"}</span>
      </button>
      {open && (
        <div className="mt-4 grid gap-4 md:grid-cols-2">
          <div>
            <div className="text-sm font-bold text-slate-300">Ask a question</div>
            <textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              rows={3}
              placeholder="e.g. How can multilingual AI be deployed across smaller government departments?"
              className="mt-2 w-full rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm text-slate-100 placeholder-slate-600 outline-none focus:border-indigo-400"
            />
            <button
              disabled={state === "sending" || text.trim().length < 5}
              onClick={async () => {
                setState("sending");
                const r = await submitQuestionAction(confId, text);
                setState(r.ok ? "sent" : "error");
                if (r.ok) setText("");
              }}
              className="mt-2 rounded-xl bg-indigo-500 px-4 py-2 text-sm font-bold text-white transition hover:bg-indigo-400 disabled:opacity-40"
            >
              {state === "sending" ? "Submitting…" : "Submit question"}
            </button>
            {state === "sent" && <p className="mt-2 text-xs font-semibold text-emerald-400">✓ Sent to moderators — approved questions appear on screen.</p>}
            {state === "error" && <p className="mt-2 text-xs font-semibold text-red-400">Couldn't submit — is the question long enough?</p>}
          </div>
          <div>
            <div className="text-sm font-bold text-slate-300">On screen now</div>
            <div className="mt-2 max-h-56 space-y-2 overflow-y-auto">
              {questions.length === 0 && <p className="text-sm text-slate-600">Approved questions appear here.</p>}
              {questions.map((q) => (
                <div key={q.id} className="rounded-xl border border-white/5 bg-white/[0.03] p-3">
                  <p className="text-sm text-slate-200">“{q.question}”</p>
                  <div className="mt-1 text-[11px] text-slate-500">{q.name} · {fmtT(q.at)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

// ── Ask Conference AI (placeholder — real AI wiring lands later) ──

const AI_CANNED: [RegExp, string][] = [
  [/summar|so far|20 minutes/i, "📋 (Preview) Summary: The morning focused on multilingual AI for public services — Dr. Meera Krishnan argued deployment is outpacing experimentation, and the DPI panel mapped what UPI-scale infrastructure teaches AI rollouts. 3 key stats and 2 resources were captured in Conference Knowledge."],
  [/governance/i, "🏛️ (Preview) On AI governance: the panel discussed balancing regulation with innovation velocity, favoring sector-specific guidelines over a single omnibus framework. See the 'AI for Governance' timeline entries."],
  [/multilingual|language/i, "🗣️ (Preview) Multilingual AI threads: inclusion requires models that speak all 22 scheduled languages; adoption is up 42% per the captured statistic. Related: the Indic LLM fine-tuning workshop resources."],
  [/who|speaker/i, "🎤 (Preview) Speakers so far are listed in the timeline with their updates — tap a speaker chip to see their profile on the conference site."],
];

function AskConferenceAI({ onClose, confName }: { onClose: () => void; confName: string }) {
  const [msgs, setMsgs] = useState<{ role: "user" | "ai"; text: string }[]>([
    { role: "ai", text: `Hi! I'm the ${confName} assistant. I answer only from this conference's knowledge — updates, sessions, quotes and resources. AI features are in preview; full transcription-grounded answers arrive soon.` },
  ]);
  const [text, setText] = useState("");
  const ask = (q: string) => {
    const answer = AI_CANNED.find(([re]) => re.test(q))?.[1] ??
      "🔎 (Preview) I'll be able to search everything said at this conference — transcripts, updates and resources — once AI features are enabled. For now, browse the timeline and Conference Knowledge panels.";
    setMsgs((m) => [...m, { role: "user", text: q }, { role: "ai", text: answer }]);
    setText("");
  };
  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/50 backdrop-blur-sm" onClick={onClose}>
      <div className="fx-in flex h-full w-full max-w-md flex-col border-l border-white/10 bg-[#0e1119] p-5" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between">
          <h2 className="text-base font-black">✨ Ask Conference AI <span className={`${chip} ml-2 bg-amber-500/15 text-amber-300`}>PREVIEW</span></h2>
          <button onClick={onClose} className="rounded-lg px-2 py-1 text-slate-500 hover:bg-white/10">✕</button>
        </div>
        <div className="mt-3 flex flex-wrap gap-1.5">
          {["What has been discussed so far?", "Summarise the last 20 minutes", "What was said about AI governance?", "Show points on multilingual AI"].map((q) => (
            <button key={q} onClick={() => ask(q)} className="rounded-full border border-white/10 bg-white/5 px-2.5 py-1 text-[11px] text-indigo-300 hover:bg-white/10">{q}</button>
          ))}
        </div>
        <div className="mt-4 flex-1 space-y-3 overflow-y-auto">
          {msgs.map((m, i) => (
            <div key={i} className={`max-w-[85%] rounded-2xl px-3.5 py-2.5 text-sm ${m.role === "ai" ? "bg-white/[0.06] text-slate-200" : "ml-auto bg-indigo-500 text-white"}`}>{m.text}</div>
          ))}
        </div>
        <form onSubmit={(e) => { e.preventDefault(); if (text.trim()) ask(text.trim()); }} className="mt-3 flex gap-2">
          <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Ask about this conference…" className="flex-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm outline-none focus:border-indigo-400" />
          <button className="rounded-xl bg-indigo-500 px-4 text-sm font-bold text-white hover:bg-indigo-400">→</button>
        </form>
      </div>
    </div>
  );
}

// ── My Notes ──────────────────────────────────────────────

function MyNotes({ notes, onClose, onRemove, onAdd, confId }: { notes: Note[]; onClose: () => void; onRemove: (id: string) => void; onAdd: (text: string) => Promise<void>; confId: string }) {
  const [text, setText] = useState("");
  void confId;
  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/50 backdrop-blur-sm" onClick={onClose}>
      <div className="fx-in flex h-full w-full max-w-md flex-col border-l border-white/10 bg-[#0e1119] p-5" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between">
          <h2 className="text-base font-black">📝 My Notes</h2>
          <button onClick={onClose} className="rounded-lg px-2 py-1 text-slate-500 hover:bg-white/10">✕</button>
        </div>
        <form onSubmit={async (e) => { e.preventDefault(); if (text.trim()) { await onAdd(text.trim()); setText(""); } }} className="mt-3 flex gap-2">
          <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Write a personal note…" className="flex-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm outline-none focus:border-indigo-400" />
          <button className="rounded-xl bg-indigo-500 px-3 text-sm font-bold text-white hover:bg-indigo-400">＋</button>
        </form>
        <div className="mt-4 flex-1 space-y-2 overflow-y-auto">
          {notes.length === 0 && <p className="text-sm text-slate-600">Save conference points with “＋ Add to My Notes”, or write your own above. Notes stay with your account.</p>}
          {notes.map((n) => (
            <div key={n.id} className="rounded-xl border border-white/5 bg-white/[0.03] p-3">
              <div className="flex items-start justify-between gap-2">
                <p className="text-sm text-slate-200">{n.title ? `📌 ${n.title}` : n.text}</p>
                <button onClick={() => onRemove(n.id)} className="text-xs text-slate-600 hover:text-red-400">✕</button>
              </div>
              {n.title && n.text && <p className="mt-1 text-xs text-slate-500">{n.text}</p>}
              <div className="mt-1 text-[11px] text-slate-600">{fmtT(n.at)}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
