/* global React, ChromeWindow, C */
const { useState, useEffect, useRef } = React;

const TABS = [
  { id: "news", title: "News article - opinion piece", url: "news-site.example/opinion/article", count: 412 },
  { id: "video", title: "Video platform - long interview", url: "video-site.example/watch?id=...", count: 88 },
  { id: "shop", title: "Online shop - product page", url: "shop.example/product/...", count: 17 },
];

// Looping product demo: an idle page with the pulsing Webzi button, a
// cursor glides over, clicks, and the sidebar slides in as an overlay —
// exactly how the real extension behaves (it overlays, it never reflows
// the host page). Phases: idle → approach → click → open → close.
const DEMO = { idle: 1400, approach: 1100, click: 350, open: 5600, close: 600 };

function useDemoLoop(paused) {
  const [phase, setPhase] = useState("idle");
  useEffect(() => {
    if (paused) { setPhase("open"); return; }
    let alive = true;
    let timer;
    const seq = [
      ["idle", DEMO.idle], ["approach", DEMO.approach], ["click", DEMO.click],
      ["open", DEMO.open], ["close", DEMO.close],
    ];
    let i = 0;
    const step = () => {
      if (!alive) return;
      setPhase(seq[i][0]);
      timer = setTimeout(() => { i = (i + 1) % seq.length; step(); }, seq[i][1]);
    };
    step();
    return () => { alive = false; clearTimeout(timer); };
  }, [paused]);
  return phase;
}

function Showcase() {
  const [tab, setTab] = useState(TABS[0]);
  const reduceMotion = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const phase = useDemoLoop(reduceMotion);
  const sidebarOpen = phase === "open" || reduceMotion;
  const cursorAtFab = phase === "approach" || phase === "click";

  return (
    <section id="how" className="mobile-section" style={showcaseStyles.wrap}>
      <SectionLabel kicker="How it works" title={<>The sidebar <em style={{ fontStyle: "italic", color: C.brandHi }}>lives</em> on the page you are reading.</>} />

      <div style={showcaseStyles.tabs}>
        {TABS.map((t) => (
          <button
            key={t.id}
            type="button"
            aria-pressed={tab.id === t.id}
            onClick={() => setTab(t)}
            style={{ ...showcaseStyles.tab, ...(tab.id === t.id ? showcaseStyles.tabActive : {}) }}
          >
            <span>{t.title.split(" - ")[0]}</span>
            <span style={showcaseStyles.tabN}>{t.count}</span>
          </button>
        ))}
      </div>

      <div data-reveal="scale" style={showcaseStyles.frame}>
        <ChromeWindow url={tab.url} tabs={[{ title: tab.title }]} width="100%" height={600}>
          <div className="showcase-split" style={{ ...showcaseStyles.split, position: "relative", overflow: "hidden" }}>
            <FakePage tab={tab} clicked={phase === "click"} fabHidden={sidebarOpen} />
            <div style={{
              position: "absolute", top: 0, right: 0, bottom: 0,
              width: "min(380px, 100%)",
              transform: sidebarOpen ? "translateX(0)" : "translateX(105%)",
              transition: "transform 0.45s cubic-bezier(0.16, 1, 0.3, 1)",
              boxShadow: sidebarOpen ? "-24px 0 60px -20px rgba(0,0,0,0.55)" : "none",
              display: "flex",
            }}>
              <Sidebar tab={tab} />
            </div>
            {!reduceMotion && <DemoCursor atFab={cursorAtFab} clicked={phase === "click"} hidden={sidebarOpen} />}
          </div>
        </ChromeWindow>
      </div>

      <div className="three-col" style={showcaseStyles.captions}>
        <Caption num="A" title="Open it on any URL" body="The Webzi button opens a focused sidebar on the page you are already reading." />
        <Caption num="B" title="Same tabs as the extension" body="Casts, Activity, Global, and Trails are shown exactly as the product is organized." />
        <Caption num="C" title="Context stays intact" body="Posts, replies, polls, notes, highlights, and trails stay tied to their original page." />
      </div>
    </section>
  );
}

function SectionLabel({ kicker, title }) {
  return (
    <div data-reveal="" style={{ marginBottom: 56, maxWidth: 820 }}>
      <div style={{ fontSize: 12, letterSpacing: 2, textTransform: "uppercase", color: C.brandHi, fontWeight: 600, marginBottom: 18 }}>
        {kicker}
      </div>
      <h2 style={{
        fontFamily: "'Instrument Serif', serif", fontWeight: 400,
        fontSize: "clamp(40px, 5vw, 72px)", lineHeight: 1.0, letterSpacing: 0,
        color: C.text, margin: 0, textWrap: "balance",
      }}>
        {title}
      </h2>
    </div>
  );
}

function FakePage({ tab, clicked, fabHidden }) {
  return (
    <div className="showcase-fake-page" style={fakePageStyles.wrap}>
      <div style={{ maxWidth: 540 }}>
        <div style={fakePageStyles.kicker}>OPINION / A NEWS SITE</div>
        <h3 style={fakePageStyles.title}>Platforms decide who gets to speak.</h3>
        <div style={fakePageStyles.byline}>By a journalist / 6 min read / today</div>
        <p style={fakePageStyles.p}>
          For years, the same pattern has repeated itself across the open web.
          <span style={fakePageStyles.highlight}> Websites quietly disable comments. Shops only show filtered reviews. You browse alone.</span>
        </p>
        <p style={fakePageStyles.p}>
          Retiola adds the conversation layer back without pulling you away from the page.
        </p>
      </div>
      <div style={{
        ...fakePageStyles.fab,
        transform: clicked ? "scale(0.86)" : "scale(1)",
        opacity: fabHidden ? 0 : 1,
        transition: "transform 0.15s ease-out, opacity 0.3s ease-out",
      }} title="Open Retiola">
        <img src="logo-gold.png" alt="" width="30" height="30" style={{ display: "block" }} />
        <span style={fakePageStyles.fabPing} />
      </div>
    </div>
  );
}

// Fake mouse cursor for the looping demo. Rests mid-page, glides to the
// Webzi button, "clicks", then fades while the sidebar takes over.
function DemoCursor({ atFab, clicked, hidden }) {
  return (
    <div aria-hidden="true" style={{
      position: "absolute",
      left: atFab ? "calc(100% - 52px)" : "46%",
      top: atFab ? "calc(100% - 46px)" : "58%",
      opacity: hidden ? 0 : 1,
      transform: clicked ? "scale(0.82)" : "scale(1)",
      transition: "left 1s cubic-bezier(0.45, 0, 0.2, 1), top 1s cubic-bezier(0.45, 0, 0.2, 1), opacity 0.35s ease-out, transform 0.12s ease-out",
      zIndex: 30, pointerEvents: "none",
      filter: "drop-shadow(0 2px 6px rgba(0,0,0,0.45))",
    }}>
      <svg width="22" height="30" viewBox="0 0 22 30">
        <path d="M2 1 L2 24 L8 19 L12 28 L16 26 L12 17 L20 16 Z" fill="#fff" stroke="#111" strokeWidth="1.4" strokeLinejoin="round" />
      </svg>
    </div>
  );
}

function Sidebar({ tab }) {
  return (
    <aside className="showcase-sidebar" style={sidebarStyles.wrap}>
      <div style={sidebarStyles.head}>
        <div style={sidebarStyles.brandRow}>
          <div style={sidebarStyles.brand}>
            <img src="logo-gold.png" alt="" width="34" height="34" style={{ display: "block", filter: "drop-shadow(0 0 10px rgba(236,167,44,0.38))" }} />
            <span style={sidebarStyles.wordmark}>Retiola</span>
          </div>
          <div style={sidebarStyles.actions}>
            <IconBtn label="AI summary">✨</IconBtn>
            <IconBtn label="Notifications">🔔</IconBtn>
            <IconBtn label="Settings">⚙</IconBtn>
            <IconBtn label="Copy link">🔗</IconBtn>
            <IconBtn label="Close">✕</IconBtn>
          </div>
        </div>

        <div style={sidebarStyles.metaRow}>
          <span style={sidebarStyles.url}>{tab.url}</span>
          <span style={sidebarStyles.presence}><span style={sidebarStyles.greenDot} /> {3 + (tab.count % 6)} here now</span>
        </div>
      </div>

      <div style={sidebarStyles.tabRail}>
        {["Casts", "Activity", "Global", "Trails"].map((name, i) => (
          <span key={name} style={{ ...sidebarStyles.viewTab, ...(i === 0 ? sidebarStyles.viewTabOn : {}) }}>{name}</span>
        ))}
        <a href="https://ko-fi.com/ambiwebz" target="_blank" rel="noopener noreferrer" style={sidebarStyles.kofi}>Donate</a>
      </div>

      <div style={sidebarStyles.body}>
        <Post rank="Orb-Weaver" rankColor={X.gold} name="techfreund" time="2m" score={47} text="This is exactly the kind of article where page-based threads make sense. The context is still right here." reactions={[["👍", 14], ["🔥", 8]]} replies={2} />
        <Poll q="Should every website have a reader discussion layer?" options={[["Yes, when readers choose it", 44], ["Only with moderation tools", 41], ["No, sites should decide", 15]]} votes={284} />
        <Post rank="Hatchling" rankColor={X.textMuted} name="surf_lisa" time="14m" score={3} text="I like that this is tied to the page, not another random feed." reactions={[["👍", 8]]} replies={0} />
      </div>

      <div style={sidebarStyles.composer}>
        <div style={sidebarStyles.input}>Add to the discussion...</div>
        <div style={sidebarStyles.composerBar}>
          <div style={{ display: "flex", gap: 6 }}>
            {["B", "I", "Q", "smile"].map((s) => <span key={s} style={sidebarStyles.tool}>{s}</span>)}
          </div>
          <button style={sidebarStyles.send}>Post -&gt;</button>
        </div>
      </div>
    </aside>
  );
}

function IconBtn({ children, label }) {
  return (
    <button type="button" aria-label={label} title={label} style={sidebarStyles.iconBtn}>
      {children}
    </button>
  );
}

function Post({ rank, rankColor, name, time, score, text, reactions, replies }) {
  return (
    <div style={postStyles.wrap}>
      <div style={postStyles.head}>
        <div style={{ ...postStyles.avatar, color: rankColor, borderColor: rankColor + "66" }}>{name[0].toUpperCase()}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={postStyles.nameRow}>
            <span style={postStyles.name}>{name}</span>
            <span style={{ ...postStyles.rank, color: rankColor, borderColor: rankColor + "55" }}>{rank}</span>
          </div>
          <span style={postStyles.time}>{time} ago</span>
        </div>
        <div style={postStyles.score}>
          <span>^</span>
          <strong>{score}</strong>
          <span>v</span>
        </div>
      </div>
      <div style={postStyles.body}>{text}</div>
      <div style={postStyles.foot}>
        <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
          {reactions.map(([e, n]) => (
            <span key={e} style={postStyles.react}>{e} <span style={{ color: C.textDim }}>{n}</span></span>
          ))}
        </div>
        <span style={postStyles.reply}>{replies} {replies === 1 ? "reply" : "replies"}</span>
      </div>
    </div>
  );
}

function Poll({ q, options, votes }) {
  const max = Math.max(...options.map(([, n]) => n));
  return (
    <div style={pollStyles.wrap}>
      <div style={pollStyles.head}>
        <span style={pollStyles.tag}>POLL</span>
        <span style={pollStyles.votes}>{votes} votes</span>
      </div>
      <div style={pollStyles.q}>{q}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 12 }}>
        {options.map(([label, pct]) => (
          <div key={label} style={pollStyles.bar}>
            <div style={{ ...pollStyles.fill, width: `${pct}%`, background: pct === max ? X.gold : X.goldDark, opacity: pct === max ? 0.9 : 0.35 }} />
            <div style={pollStyles.barLabel}>
              <span>{label}</span>
              <span style={{ fontWeight: 700 }}>{pct}%</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Caption({ num, title, body }) {
  return (
    <div data-reveal="">
      <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 38, color: C.brandHi, lineHeight: 1, fontStyle: "italic" }}>{num}</div>
      <div style={{ color: C.text, fontSize: 17, fontWeight: 600, marginTop: 12, letterSpacing: 0 }}>{title}</div>
      <div style={{ color: C.textDim, fontSize: 14, lineHeight: 1.55, marginTop: 6 }}>{body}</div>
    </div>
  );
}

// Real extension palette — mirrors tailwind.config.js (OLED spec, Design
// Handout v1). The sidebar mockup must look like the actual product, not
// like the website's purple panels.
const X = {
  bg: "#050505",
  deepest: "#000000",
  card: "#0B0B0B",
  border: "#1F1F1F",
  hover: "#151515",
  gold: "#F6B73D",
  goldLight: "#FFD066",
  goldDark: "#C68A1C",
  text: "#FFFFFF",
  textSec: "#BDB8C7",
  textMuted: "#777088",
};

const showcaseStyles = {
  wrap: { padding: "120px 36px", maxWidth: 1280, margin: "0 auto" },
  tabs: { display: "flex", gap: 8, marginBottom: 18, flexWrap: "wrap" },
  tab: {
    display: "inline-flex", alignItems: "center", gap: 8,
    padding: "8px 14px", borderRadius: 999,
    background: "transparent", border: `1px solid ${C.border}`,
    color: C.textDim, fontSize: 13, cursor: "pointer", fontWeight: 500,
  },
  tabActive: { background: C.panel, borderColor: C.borderHi, color: C.text },
  tabN: { color: C.brandHi, fontSize: 11, fontWeight: 700 },
  frame: {
    position: "relative", borderRadius: 18, overflow: "visible",
    boxShadow: "0 60px 120px -40px rgba(198,138,28,0.35), 0 0 0 1px rgba(255,255,255,0.06)",
  },
  split: { display: "flex", height: 540, background: "#fafafa" },
  captions: { display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24, marginTop: 64 },
};

const fakePageStyles = {
  wrap: {
    flex: 1, padding: "40px 56px", background: "#fafafa", color: "#1a1a1a",
    fontFamily: "Georgia, serif", position: "relative", overflow: "hidden", minHeight: 540,
  },
  kicker: { fontFamily: "system-ui, sans-serif", fontSize: 11, letterSpacing: 2, color: "#777", fontWeight: 700, marginBottom: 16 },
  title: { fontSize: 32, lineHeight: 1.1, letterSpacing: 0, margin: "0 0 14px", fontWeight: 700 },
  byline: { fontFamily: "system-ui, sans-serif", fontSize: 12, color: "#777", marginBottom: 28 },
  p: { fontSize: 16, lineHeight: 1.65, margin: "0 0 16px" },
  highlight: { background: "rgba(236,167,44,0.28)", padding: "1px 0", borderBottom: `2px solid ${C.brand}` },
  fab: {
    position: "absolute", bottom: 24, right: 24,
    width: 52, height: 52, borderRadius: "50%",
    background: "#000", border: `2px solid ${X.gold}`,
    display: "flex", alignItems: "center", justifyContent: "center",
    boxShadow: "0 12px 30px -10px rgba(198,138,28,0.6), 0 0 0 6px rgba(236,167,44,0.12)",
  },
  fabPing: {
    position: "absolute", inset: -2, borderRadius: "50%",
    border: `2px solid ${C.brandHi}`, animation: "pingRing 2s ease-out infinite", pointerEvents: "none",
  },
};

const sidebarStyles = {
  wrap: {
    width: 380, flexShrink: 0, background: X.bg, color: X.text,
    borderLeft: `1px solid ${X.border}`, display: "flex", flexDirection: "column",
    fontFamily: "system-ui, -apple-system, sans-serif",
  },
  head: { padding: "12px 14px 10px", borderBottom: `1px solid ${X.border}`, background: X.deepest },
  brandRow: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 },
  brand: { display: "flex", alignItems: "center", gap: 8, minWidth: 0 },
  wordmark: { fontFamily: "'Cinzel', serif", fontSize: 18, fontWeight: 700, color: X.text, whiteSpace: "nowrap", letterSpacing: 0.5 },
  wordmarkZ: { color: X.gold, fontStyle: "normal", marginLeft: -1 },
  actions: { display: "flex", gap: 4, flexShrink: 0 },
  iconBtn: {
    width: 26, height: 26, borderRadius: 8, border: `1px solid ${X.border}`,
    background: "transparent", color: X.textSec, fontSize: 12,
    display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
  },
  metaRow: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginTop: 10, fontSize: 10.5, color: X.textSec },
  url: { minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontFamily: "'JetBrains Mono', monospace", color: X.gold },
  presence: { display: "inline-flex", alignItems: "center", gap: 5, flexShrink: 0 },
  greenDot: { width: 6, height: 6, borderRadius: "50%", background: "#34D399", boxShadow: "0 0 6px rgba(52,211,153,0.7)", animation: "blink 1.4s ease-in-out infinite" },
  tabRail: { display: "flex", alignItems: "center", gap: 4, padding: "7px 10px", borderBottom: `1px solid ${X.border}`, background: X.deepest, overflowX: "auto" },
  viewTab: { padding: "6px 10px", color: X.textMuted, cursor: "pointer", borderRadius: 8, fontSize: 11.5, whiteSpace: "nowrap" },
  viewTabOn: { color: X.text, background: X.hover, fontWeight: 700, boxShadow: `inset 0 -2px 0 ${X.gold}` },
  kofi: { marginLeft: "auto", padding: "5px 8px", borderRadius: 999, border: "1px solid rgba(255,94,91,0.35)", color: "#ffaaa8", textDecoration: "none", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" },
  body: { flex: 1, overflow: "auto", padding: "12px 14px", display: "flex", flexDirection: "column", gap: 10, background: X.bg },
  composer: { padding: 12, borderTop: `1px solid ${X.border}`, background: X.card },
  input: { padding: "10px 12px", border: `1px solid ${X.border}`, borderRadius: 10, background: X.deepest, marginBottom: 8, color: X.textMuted, fontSize: 13 },
  composerBar: { display: "flex", justifyContent: "space-between", alignItems: "center" },
  tool: { minWidth: 26, height: 26, padding: "0 6px", display: "inline-flex", alignItems: "center", justifyContent: "center", color: X.textSec, fontSize: 11, cursor: "pointer", borderRadius: 6, border: `1px solid ${X.border}` },
  send: { background: X.gold, color: "#000", border: "none", padding: "7px 16px", borderRadius: 999, fontSize: 12.5, fontWeight: 800, cursor: "pointer" },
};

const postStyles = {
  wrap: { padding: 12, border: `1px solid ${X.border}`, borderRadius: 12, background: X.card },
  head: { display: "flex", alignItems: "center", gap: 10 },
  avatar: { width: 30, height: 30, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(255,255,255,0.06)", border: "1px solid", fontWeight: 800, fontSize: 13 },
  nameRow: { display: "flex", alignItems: "center", gap: 6, minWidth: 0, flexWrap: "wrap" },
  name: { color: X.text, fontWeight: 700, fontSize: 13 },
  rank: { fontSize: 9.5, padding: "1px 6px", borderRadius: 999, border: "1px solid", textTransform: "uppercase", letterSpacing: 0, fontWeight: 700 },
  time: { color: X.textMuted, fontSize: 11 },
  score: { display: "flex", flexDirection: "column", alignItems: "center", gap: 1, padding: "4px 6px", borderRadius: 6, background: X.deepest, border: `1px solid ${X.border}`, color: X.textSec, fontSize: 10 },
  body: { color: X.textSec, fontSize: 13.5, lineHeight: 1.55, margin: "10px 0" },
  foot: { display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 },
  react: { display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 8px", borderRadius: 999, background: X.deepest, border: `1px solid ${X.border}`, fontSize: 11.5, color: X.textSec },
  reply: { color: X.textMuted, fontSize: 12, whiteSpace: "nowrap" },
};

const pollStyles = {
  wrap: { padding: 14, border: `1px solid rgba(246,183,61,0.35)`, borderRadius: 12, background: `linear-gradient(180deg, ${X.hover}, ${X.card})` },
  head: { display: "flex", justifyContent: "space-between", alignItems: "center" },
  tag: { fontSize: 10, color: X.gold, fontWeight: 800, letterSpacing: 1 },
  votes: { color: X.textMuted, fontSize: 11 },
  q: { color: X.text, fontSize: 14, fontWeight: 700, marginTop: 6, lineHeight: 1.4 },
  bar: { position: "relative", minHeight: 28, borderRadius: 6, background: X.deepest, overflow: "hidden" },
  fill: { position: "absolute", inset: 0, borderRadius: 6, transition: "width 0.4s" },
  barLabel: { position: "relative", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, padding: "0 10px", minHeight: 28, fontSize: 12, color: X.text },
};

Object.assign(window, { Showcase, SectionLabel });
