// Shared atoms + helpers
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ===== Icons (lucide-style inline SVG so we don't depend on runtime resolution) =====
const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.75, strokeLinecap: "round", strokeLinejoin: "round" };
const Icon = ({ size = 18, children, style }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" {...stroke} style={style}>{children}</svg>
);
const IconArrowRight = (p) => <Icon {...p}><path d="M5 12h14"/><path d="m13 6 6 6-6 6"/></Icon>;
const IconArrowUpRight = (p) => <Icon {...p}><path d="M7 17 17 7"/><path d="M7 7h10v10"/></Icon>;
const IconCheck = (p) => <Icon {...p}><path d="M20 6 9 17l-5-5"/></Icon>;
const IconX = (p) => <Icon {...p}><path d="M18 6 6 18"/><path d="m6 6 12 12"/></Icon>;
const IconReply = (p) => <Icon {...p}><path d="m9 17-5-5 5-5"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></Icon>;
const IconRotateLeft = (p) => <Icon {...p}><path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/></Icon>;
const IconZap = (p) => <Icon {...p}><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8Z"/></Icon>;
const IconBot = (p) => <Icon {...p}><rect x="3" y="8" width="18" height="12" rx="3"/><path d="M12 2v6"/><circle cx="9" cy="14" r="1.2" fill="currentColor"/><circle cx="15" cy="14" r="1.2" fill="currentColor"/></Icon>;
const IconLayers = (p) => <Icon {...p}><path d="m12 2 9 5-9 5-9-5 9-5Z"/><path d="m3 12 9 5 9-5"/><path d="m3 17 9 5 9-5"/></Icon>;
const IconShield = (p) => <Icon {...p}><path d="M12 3 4 6v6c0 5 4 8 8 9 4-1 8-4 8-9V6l-8-3Z"/></Icon>;
const IconSpark = (p) => <Icon {...p}><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></Icon>;
const IconClock = (p) => <Icon {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></Icon>;
const IconMail = (p) => <Icon {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></Icon>;
const IconSearch = (p) => <Icon {...p}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></Icon>;
const IconSliders = (p) => <Icon {...p}><path d="M4 6h10"/><path d="M18 6h2"/><path d="M4 12h2"/><path d="M10 12h10"/><path d="M4 18h14"/><path d="M20 18h0"/><circle cx="16" cy="6" r="2"/><circle cx="8" cy="12" r="2"/></Icon>;
const IconSend = (p) => <Icon {...p}><path d="m22 2-7 20-4-9-9-4 20-7Z"/><path d="M22 2 11 13"/></Icon>;
const IconWand = (p) => <Icon {...p}><path d="M15 4V2M15 16v-2M8 9h2M20 9h2M17.8 11.8l1.4 1.4M12.2 6.2l1.4 1.4M17.8 6.2l1.4-1.4M3 21l12-12"/></Icon>;
const IconDot = ({ color = "currentColor", size = 6 }) => (
  <span style={{ display: "inline-block", width: size, height: size, borderRadius: "50%", background: color }} />
);
const IconStar = (p) => <Icon {...p}><path d="M12 3l2.6 5.6 6.1.6-4.6 4.3 1.3 6L12 16.8 6.6 19.5l1.3-6L3.3 9.2l6.1-.6L12 3Z"/></Icon>;

// ===== MockBrowser frame — chrome around a product screenshot =====
const MockBrowser = ({ children, label = "qlivo.app", height = 460, style = {} }) => (
  <div style={{
    background: "var(--bg-2)",
    border: "1px solid var(--border)",
    borderRadius: 14,
    overflow: "hidden",
    boxShadow: "0 30px 80px -20px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.03)",
    width: "100%",
    maxWidth: "100%",
    ...style,
  }}>
    <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderBottom: "1px solid var(--border-soft)", background: "var(--bg-3)" }}>
      <div style={{ display: "flex", gap: 6 }}>
        <span style={{ width: 10, height: 10, borderRadius: 5, background: "#3A3A45" }} />
        <span style={{ width: 10, height: 10, borderRadius: 5, background: "#3A3A45" }} />
        <span style={{ width: 10, height: 10, borderRadius: 5, background: "#3A3A45" }} />
      </div>
      <div className="mono" style={{ flex: 1, textAlign: "center", fontSize: 11, color: "var(--text-4)", letterSpacing: "0.08em" }}>{label}</div>
      <div style={{ width: 30 }} />
    </div>
    <div style={{ height, position: "relative", overflow: "hidden" }}>
      {children}
    </div>
  </div>
);

// ===== Viewport helper =====
const useIsMobile = (breakpoint = 900) => {
  const query = `(max-width: ${breakpoint}px)`;
  const [isMobile, setIsMobile] = useState(
    () => typeof window !== "undefined" && window.matchMedia(query).matches
  );
  useEffect(() => {
    const mq = window.matchMedia(query);
    const onChange = (e) => setIsMobile(e.matches);
    setIsMobile(mq.matches);
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, [query]);
  return isMobile;
};

// ===== Section header =====
const SectionHeader = ({ tag, title, sub, align = "left", maxWidth = 720 }) => (
  <div style={{ textAlign: align, maxWidth, margin: align === "center" ? "0 auto" : undefined }}>
    {tag && (
      <div className="label" style={{ display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 18, color: "var(--accent-2)" }}>
        <span className="hide-mobile-decor" style={{ width: 22, height: 1, background: "var(--accent-2)" }} />
        {tag}
      </div>
    )}
    <h2 className="section-title">{title}</h2>
    {sub && <p className="section-sub">{sub}</p>}
  </div>
);

// ===== Email card body (used in hero auto-demo, features, interactive demo) =====
const EmailCard = ({ email, dim = false, compact = false, showAi = true }) => {
  const priorityColor = {
    "急": "var(--red)",
    "高": "var(--orange)",
    "中": "var(--accent-2)",
    "低": "var(--text-3)",
  }[email.priority] || "var(--text-3)";
  return (
    <div style={{
      width: "100%",
      height: "100%",
      background: "var(--panel)",
      border: "1px solid var(--border)",
      borderRadius: 18,
      padding: compact ? 18 : 24,
      display: "flex",
      flexDirection: "column",
      gap: compact ? 12 : 16,
      color: "var(--text)",
      opacity: dim ? 0.4 : 1,
      pointerEvents: dim ? "none" : "auto",
    }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: email.color || "#1F2937", display: "flex", alignItems: "center", justifyContent: "center", color: "white", fontWeight: 700, fontSize: 13, fontFamily: "var(--font-sans)" }}>
            {email.initials}
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text)" }}>{email.senderName}</div>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>{email.senderEmail}</div>
          </div>
        </div>
        <div className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>{email.time}</div>
      </div>

      {/* Subject */}
      <div style={{ fontSize: compact ? 16 : 19, fontWeight: 700, lineHeight: 1.3, letterSpacing: "-0.01em" }}>
        {email.subject}
      </div>

      {/* AI labels */}
      {showAi && (
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          <span className="mono" style={{
            fontSize: 10,
            padding: "5px 9px",
            borderRadius: 999,
            background: "rgba(59,130,246,0.12)",
            color: "var(--accent-2)",
            border: "1px solid rgba(59,130,246,0.25)",
            fontWeight: 600,
            letterSpacing: "0.05em",
          }}>{email.category}</span>
          <span className="mono" style={{
            fontSize: 10,
            padding: "5px 9px",
            borderRadius: 999,
            background: "rgba(255,255,255,0.03)",
            color: priorityColor,
            border: `1px solid ${priorityColor}33`,
            fontWeight: 600,
            letterSpacing: "0.05em",
          }}>優先 · {email.priority}</span>
          {email.deadline && (
            <span className="mono" style={{
              fontSize: 10,
              padding: "5px 9px",
              borderRadius: 999,
              background: "rgba(255,255,255,0.03)",
              color: "var(--text-3)",
              border: "1px solid var(--border)",
              fontWeight: 600,
              letterSpacing: "0.05em",
              display: "inline-flex", gap: 5, alignItems: "center",
            }}><IconClock size={10}/> {email.deadline}</span>
          )}
        </div>
      )}

      {/* AI summary */}
      {showAi && (
        <div style={{
          background: "rgba(34,211,238,0.05)",
          border: "1px solid rgba(34,211,238,0.18)",
          borderRadius: 12,
          padding: compact ? 12 : 14,
        }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--cyan)", letterSpacing: "0.12em", marginBottom: 8, display: "flex", gap: 6, alignItems: "center" }}>
            <IconSpark size={11}/> AI 摘要
          </div>
          <div style={{ fontSize: 13, lineHeight: 1.55, color: "var(--text-2)" }}>{email.summary}</div>
        </div>
      )}

      {/* Next step */}
      {showAi && email.nextStep && (
        <div style={{ display: "flex", gap: 10, alignItems: "flex-start", padding: "10px 0 0", borderTop: "1px dashed var(--border)" }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--text-4)", letterSpacing: "0.12em", paddingTop: 2 }}>NEXT</div>
          <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.5 }}>{email.nextStep}</div>
        </div>
      )}

      {/* Body preview */}
      {!showAi && (
        <div style={{ fontSize: 13, color: "var(--text-3)", lineHeight: 1.6, flex: 1, overflow: "hidden" }}>
          {email.preview}
        </div>
      )}
    </div>
  );
};

// ===== Sample dataset shared across hero demo + interactive demo =====
const SAMPLE_EMAILS = [
  {
    id: "e1",
    senderName: "林佳穎 / 凱盛電子",
    senderEmail: "ginny.lin@kaisheng.com.tw",
    initials: "JL",
    color: "linear-gradient(135deg, #3B82F6, #1D4ED8)",
    time: "09:24",
    subject: "MLCC 電容 FC-104K-50V 報價需求（5/22 前）",
    category: "客戶詢價",
    priority: "急",
    deadline: "5/22 12:00",
    summary: "凱盛電子採購評估批次工業控制板用 MLCC，需求 50,000 pcs，要求單價／級距／交期／付款條件，5/22 前回覆。",
    nextStep: "請業務確認現貨後回覆報價單與付款條件",
    preview: "您好，我們目前正在評估一批用於工業控制板的 MLCC 電容…",
    swipe: "right",
    swipeMeaning: "立即回覆",
    replyRough: "林採購您好，\n收到詢價，MLCC FC-104K-50V 我們可以做 50K，下週給報價。\n謝謝\n王志明",
    replyOptimized: "林採購您好，\n感謝您的詢價。針對 MLCC 電容 FC-104K-50V（0.1uF / 50V / X7R / 0603），依您 50,000 pcs 需求，建議單價 NT$0.42 / pcs（級距 30K / 50K / 100K），標準交期 4 週，目前現貨可支應首批 30K。付款條件 T/T 30 days，運費由本公司負擔。完整報價單將於今日下午另附 PDF 寄出。\n敬祝商祺\n王志明",
  },
  {
    id: "e2",
    senderName: "Allen Hsu / Product",
    senderEmail: "allen@qlivo.internal",
    initials: "AH",
    color: "linear-gradient(135deg, #8B5CF6, #6D28D9)",
    time: "08:51",
    subject: "Q3 OKR Review — 下週四 14:00 跨部門會議",
    category: "內部協作",
    priority: "中",
    deadline: "下週四",
    summary: "Allen 邀請參加 Q3 OKR review，需準備 PM／Eng／Design 三方進度，預估 60 分鐘。",
    nextStep: "確認時間並上傳上週的 KR 數字到共享文件",
    preview: "Hi team, 為了同步 Q3 各 KR 的進度，我安排下週四…",
    swipe: "left",
    swipeMeaning: "稍後處理",
    replyRough: "Allen, 收到，下週四 OK，我會準備 KR 數字。",
    replyOptimized: "Allen 您好，\n收到 Q3 OKR Review 邀請，下週四 14:00 可以配合。我會在會議前一天將 PM 端的 KR 進度（含風險與調整建議）上傳至共享文件，並請 Eng/Design 同步準備自己負責的 KR。\n如需調整議程或補充材料，請隨時告知。",
  },
  {
    id: "e3",
    senderName: "Newsletter Weekly",
    senderEmail: "digest@newsletter.io",
    initials: "NW",
    color: "linear-gradient(135deg, #525266, #2A2A36)",
    time: "06:00",
    subject: "本週 12 則矽谷新創動態（含 OpenAI、Anthropic）",
    category: "電子報",
    priority: "低",
    deadline: null,
    summary: "週報合輯，主要為矽谷新創融資與產品新聞，含 3 則與 AI Coding 相關的長文。",
    nextStep: "週末有空再看，或交給 AI 摘要重點",
    preview: "This week: OpenAI ships codename Sage, Anthropic raised…",
    swipe: "left",
    swipeMeaning: "稍後處理",
    replyRough: "謝謝週報，我會找時間看。",
    replyOptimized: "Hi，\n感謝本週的週報整理，AI Coding 相關的三篇我會優先閱讀。如方便，能否在下週的合輯中加上「企業導入 AI 工作流」相關的案例？這對我們團隊的決策很有參考價值。\n再次感謝。",
  },
];

// ===== Export everything to window =====
Object.assign(window, {
  React, useState, useEffect, useRef, useMemo, useCallback, useIsMobile,
  IconArrowRight, IconArrowUpRight, IconCheck, IconX, IconReply, IconRotateLeft,
  IconZap, IconBot, IconLayers, IconShield, IconSpark, IconClock, IconMail,
  IconSearch, IconSliders, IconSend, IconWand, IconDot, IconStar,
  MockBrowser, SectionHeader, EmailCard, SAMPLE_EMAILS,
});
