// F3 · 分手塔罗牌 — Screen components

const { useState, useEffect, useMemo, useRef } = React;

const POSITIONS = [
  { id: "past", label: "过去 · Past", whisper: "今夜你带进来的重量。", en: "Past" },
  { id: "present", label: "此刻 · Present", whisper: "正在写下这条消息的你。", en: "Present" },
  { id: "future", label: "去向 · Future", whisper: "如果照这个轨道继续，你会去向哪里。", en: "Future" },
];

// (Landing is defined in landing.jsx)

// ====================== PICKING ======================
function Picking({ deck, picks, onPick, onCancel }) {
  const slotIdx = picks.length;
  const total = deck.length; // 78

  // fan layout — full 78-card spread (gentle arc; edges stay near viewport bottom)
  const FAN_ARC = 36; // total degrees
  const angleStep = FAN_ARC / (total - 1);
  const startAngle = -FAN_ARC / 2;

  return (
    <div className="fan-stage" data-screen-label="02 Picking">
      <div className="fan-header">
        <div className="step-dots">
          {POSITIONS.map((p, i) => (
            <span key={p.id}
              className={i < slotIdx ? "done" : i === slotIdx ? "now" : ""} />
          ))}
        </div>
        <h2 className="fadeup">
          请为<em> {slotIdx < 3 ? POSITIONS[slotIdx].label.split(" · ")[0] : "..."} </em>选一张
        </h2>
        <p className="whisper fadeup" style={{ animationDelay: "0.1s" }}>
          {slotIdx < 3 ? POSITIONS[slotIdx].whisper : "三张已就位..."}
        </p>
      </div>

      <div className="slots fadeup" style={{ animationDelay: "0.2s" }}>
        {POSITIONS.map((pos, i) => {
          const picked = picks[i];
          const isActive = i === slotIdx;
          return (
            <div key={pos.id} className="slot">
              <div className={`slot-label ${isActive ? "active" : ""}`}>
                {pos.label.split(" · ")[0]}
              </div>
              <div className={`slot-box ${picked ? "filled" : isActive ? "active" : ""}`}>
                {picked ? (
                  <div className="slot-card">
                    <div className="or">{picked.orientation === "upright" ? "正位" : "逆位"}</div>
                    <div className="nm">{picked.card.zh}</div>
                    <div className="en">{picked.card.en}</div>
                  </div>
                ) : (
                  <span style={{
                    fontFamily: "var(--font-mono)",
                    fontSize: 18,
                    color: "var(--mute)",
                    opacity: 0.5,
                  }}>{i + 1}</span>
                )}
              </div>
            </div>
          );
        })}
      </div>

      <div className="fan-deck-wrap">
        {deck.map((c, i) => {
          const angle = startAngle + i * angleStep;
          const isPicked = picks.some((p) => p.deckIdx === i);
          return (
            <div
              key={i}
              className={`fan-card ${isPicked ? "is-picked" : ""}`}
              style={{
                transform: `rotate(${angle}deg)`,
                zIndex: i,
              }}
              onClick={() => !isPicked && slotIdx < 3 && onPick(c, i)}
            >
              <div className="card-back-wrap">
                <span className="glow" />
                <CardBack />
              </div>
            </div>
          );
        })}
      </div>

      <button className="cancel-link" onClick={onCancel}>← 回到草稿</button>
    </div>
  );
}

// ====================== READING (wait) ======================
function Reading({ picks, ready, error, onDone, onRetry }) {
  // Minimum dwell time (3.2s) so the cards & language can register;
  // wait beyond that only if the LLM is still working.
  const [minMet, setMinMet] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setMinMet(true), 3200);
    return () => clearTimeout(t);
  }, []);

  useEffect(() => {
    if (minMet && ready && !error) onDone();
  }, [minMet, ready, error]);

  return (
    <div className="reading-stage" data-screen-label="03 Reading">
      <div className="eyebrow fadeup">
        {error ? "解读卡住了 · the line stalled" : "正在解读你的牌阵"}
      </div>

      <div className="reveal-row">
        {picks.map((p, i) => (
          <div key={i} className="reveal-card">
            <div className="label">{POSITIONS[i].label.split(" · ")[0]} · {POSITIONS[i].en}</div>
            <div className="face">
              {p.orientation === "reversed" && <div className="reversed-tag">逆位 · Reversed</div>}
              {p.orientation === "upright" && <div className="reversed-tag" style={{ color: "var(--gold)" }}>正位 · Upright</div>}
              <div className="name-zh">{p.card.zh}</div>
              <div className="name-en">{p.card.en}</div>
              <div className="keyword">{p.orientation === "upright" ? p.card.upright : p.card.reversed}</div>
            </div>
            <div className="meaning">{p.orientation === "upright" ? p.card.upright : p.card.reversed}</div>
          </div>
        ))}
      </div>

      {!error && (
        <div className="thinking fadeup" style={{ animationDelay: "1.2s" }}>
          <div className="dots"><i /><i /><i /></div>
          <span>正在读你写下的，和你没有写下的</span>
        </div>
      )}

      {error && (
        <div className="fadeup" style={{ textAlign: "center", maxWidth: 420 }}>
          <p style={{ color: "var(--gold)", fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 15, lineHeight: 1.6, marginBottom: 20 }}>
            线上有点静电 · 你的牌还在这里 —— 再试一次。
          </p>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--mute)", marginBottom: 18, letterSpacing: "0.12em" }}>
            {error}
          </div>
          <button className="btn" onClick={onRetry}>再试一次 →</button>
        </div>
      )}
    </div>
  );
}

// ====================== RESULT (teaser + unlock) ======================
function Result({ picks, paid, reading, onPay, onRestart }) {
  const past = picks[0], present = picks[1], future = picks[2];
  const oz = (o) => o === "upright" ? "正位" : "逆位";

  // Use generated text when available; keep a graceful fallback for interrupted reads.
  const briefText = reading?.brief
    || `深夜两点，你又打开了和他的对话框。屏幕的蓝光映着你的犹豫——这条消息已经被你改了七遍。\n\n${past?.card?.zh} ${oz(past?.orientation)}落在过去：你一直在重复同一个模式。${present?.card?.zh} ${oz(present?.orientation)}在现在的位置：此刻你内心涌动的是混合着渴望和恐惧的张力。${future?.card?.zh} ${oz(future?.orientation)}指向未来：当下的选择会固化成明天的习惯。\n\n牌面的倾向是：今晚先放下手机。但这只是三张牌的初读——完整的解读会告诉你为什么，以及接下来的一小时你可以做什么。`;
  const deepText = reading?.deep
    || `完整解读会在这里展开。包含：开场情绪 → ${past?.card?.zh} ${oz(past?.orientation)} 解读你今晚的回路 → ${present?.card?.zh} ${oz(present?.orientation)} 解读你正在做的事 → ${future?.card?.zh} ${oz(future?.orientation)} 解读这条路通向哪里 → 发 / 别发 / 等等的判决 → 一段 60 分钟内可以做完的小仪式。`;

  const renderProse = (text) => text.split(/\n\s*\n/).map((para, i) => (
    <p key={i}>{para.trim()}</p>
  ));

  return (
    <div className="stage" data-screen-label={paid ? "05 Result-Paid" : "04 Result-Teaser"}>
      <main className="result-shell">
        <div className="eyebrow fadeup">
          {paid ? "完整解读 · 已解锁" : "你的牌阵已就位 · 节选预览"}
        </div>
        <h1 className="fadeup" style={{
          fontFamily: "var(--font-display, var(--font-sans))",
          fontWeight: 500,
          fontSize: 38,
          letterSpacing: "-0.01em",
          margin: "16px 0 6px",
          lineHeight: 1.15,
          animationDelay: "0.1s",
        }}>
          深呼吸 ——<br />
          <span style={{
            fontFamily: "var(--font-serif)",
            fontStyle: "italic",
            background: "linear-gradient(110deg, var(--lavender), var(--mist), var(--gold-soft))",
            WebkitBackgroundClip: "text",
            backgroundClip: "text",
            color: "transparent",
          }}>
            牌阵替你看了一遍
          </span>
        </h1>
        <p className="fadeup" style={{
          color: "var(--ink-soft)",
          fontSize: 15,
          margin: "0 0 0",
          fontFamily: "var(--font-serif)",
          fontStyle: "italic",
          animationDelay: "0.2s",
        }}>
          根据你写下的草稿 +「{past?.card?.zh} → {present?.card?.zh} → {future?.card?.zh}」三张牌生成。
        </p>

        <div className="result-cards fadeup" style={{ animationDelay: "0.3s" }}>
          {picks.map((p, i) => (
            <div key={i} className="result-card">
              <div className="pos">{POSITIONS[i].label.split(" · ")[0]} · {POSITIONS[i].en}</div>
              <div className="nm">{p.card.zh}</div>
              <div className="en">{p.card.en}</div>
              <div className="or">{oz(p.orientation)} · {p.orientation === "upright" ? "Upright" : "Reversed"}</div>
            </div>
          ))}
        </div>

        <div className="teaser-wrap fadeup" style={{ animationDelay: "0.5s", marginTop: 30 }}>
          {!paid && (
            <>
              <div className="brief-label">简短报告 · 免费</div>
              <div className="read-body brief-body">
                {renderProse(briefText)}
              </div>
              <div className="teaser-fade"><span>解锁深度解读，看完整心理分析 + 明确判决 + 下一小时仪式</span></div>
            </>
          )}
          {paid && (
            <>
              <div className="brief-label" style={{ color: "var(--gold)" }}>深度报告 · 已解锁</div>
              <div className="read-body">
                {renderProse(deepText)}
              </div>
            </>
          )}
        </div>

        {!paid && (
          <div className="unlock-card fadeup" style={{ animationDelay: "0.6s" }}>
            <h3>解锁深度报告 <em>(完整分析 · 判决 · 仪式)</em></h3>
            <p className="lead">
              你已经看到三张牌在说什么——深度报告会告诉你为什么，以及接下来该怎么做。
            </p>
            <ul>
              <li>每张牌的完整心理化解读——不是泛泛的牌义，而是针对你今晚的模式</li>
              <li>针对你草稿里"那句话"的具体拆解</li>
              <li>明确的 Verdict：发 / 别发 / 等等，以及一句话理由</li>
              <li>60 分钟仪式：今晚你可以为自己做的一件小事</li>
            </ul>
            <div className="price-row">
              <div className="price">¥ 9.9<span className="unit">/ 一次解读</span></div>
              <button className="btn gold" onClick={onPay}>解锁深度报告 →</button>
            </div>
          </div>
        )}

        {paid && (
          <>
            <div className="verdict-card fadeup" style={{ animationDelay: "0.65s" }}>
              <div className="stamp"><em>Verdict</em>今晚先别发</div>
              <div className="stamp-body">
                这不是否定你的感受，而是把决定权从冲动手里拿回来。让这条草稿先过一夜，
                明早你再决定要表达什么，而不是今晚决定要被谁回应。
              </div>
            </div>

            <div className="next-hour fadeup" style={{ animationDelay: "0.75s" }}>
              <h4>Next 60 minutes</h4>
              <p>复制这条草稿到备忘录，把聊天窗口关掉，计时 20 分钟。时间到之前只做一件事：写下“我真正想被听见的是……”</p>
              <div className="perm">你可以很想他，也可以不把今晚交给他。</div>
            </div>
          </>
        )}

        <div style={{
          marginTop: 50,
          paddingTop: 28,
          borderTop: "1px solid color-mix(in oklch, var(--line) 50%, transparent)",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          fontFamily: "var(--font-mono)",
          fontSize: 11,
          letterSpacing: "0.1em",
          color: "var(--mute)",
        }}>
          <span>F3 · 午夜解读完成</span>
          <button onClick={onRestart} style={{ color: "var(--mute)", textDecoration: "underline", textUnderlineOffset: 4 }}>
            再抽一次牌
          </button>
        </div>
      </main>
    </div>
  );
}

window.Picking = Picking;
window.Reading = Reading;
window.Result = Result;
window.POSITIONS = POSITIONS;
