// reveal.jsx — 結果発表：2ページ構成（API連携版）
// diagnosis prop で受け取ったDIAGNOSIS_JSON_SPEC形式のデータを表示

function RevealScreen({ diagnosis, theme, onReset, onProductTap, productSearchStart }) {
  const RakutenProductCard = window.RakutenProductCard;
  const normalizeProductList = window.normalizeProductList;
  const ElapsedTimer = window.ElapsedTimer;
  const [phase, setPhase] = React.useState(0);
  const [page, setPage] = React.useState("report");
  const dx = diagnosis;
  const contentRef = React.useRef(null);

  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), 1400);
    const t2 = setTimeout(() => setPhase(2), 2600);
    const t3 = setTimeout(() => setPhase(3), 3400);
    const t4 = setTimeout(() => setPhase(4), 5000);
    return () => [t1, t2, t3, t4].forEach(clearTimeout);
  }, []);

  React.useEffect(() => {
    const stage = document.querySelector(".rv-stage");
    if (stage) stage.scrollTo({ top: 0, behavior: "smooth" });
  }, [page]);

  if (!dx || !dx.ranking) return null;

  const maxScore = Math.max(...dx.ranking.map((r) => r.score));

  const goProducts = () => setPage("products");
  const goReport = () => setPage("report");

  return (
    <div className={`rv-stage rv-phase-${phase}`}>
      <div className="rv-fog rv-fog-1" />
      <div className="rv-fog rv-fog-2" />
      <div className="rv-fog rv-fog-3" />

      <div className="rv-calc">
        <div className="rv-calc-ring">
          <div className="rv-calc-ring-inner" />
          <div className="rv-calc-ring-outer" />
        </div>
        <div className="rv-calc-text">
          <span>潜在意識を読み取っています</span>
          <span className="rv-calc-dots"><i></i><i></i><i></i></span>
        </div>
      </div>

      <div className="rv-title">
        <div className="rv-title-eyebrow">
          {page === "report" ? "DIAGNOSIS · あなたの潜在意識" : "RECOMMENDATION · あなたの欲しいもの"}
        </div>
        <h1 className="rv-title-h1" key={page}>
          {(page === "report" ? "潜在意識の解析結果" : "あなたの欲しいもの").split("").map((c, i) => (
            <span key={i} className="rv-title-w" style={{ animationDelay: `${i * 0.04}s` }}>{c}</span>
          ))}
        </h1>
      </div>

      <div className="rv-content" ref={contentRef}>

        {page === "report" && (
          <div className="rv-page rv-page-report" key="report">
            <div className="rv-scroll-hint">
              <span className="rv-scroll-hint-dot" />
              <span className="rv-scroll-hint-text">
                下までスクロールすると、あなたに刺さる<strong>{dx.products ? dx.products.length : 5}つの商品</strong>が見られます
              </span>
              <span className="rv-scroll-hint-arrow">↓</span>
            </div>

            <section className="rv-card-block rv-chart">
              <div className="rv-block-head">
                <div className="rv-block-tag">PARAMETER RANKING · 潜在意識の解像</div>
                <div className="rv-block-meta">{dx.ranking.length} dimensions</div>
              </div>
              <div className="rv-vchart">
                <div className="rv-vchart-grid">
                  <div className="rv-vchart-gridline" style={{ bottom: "0%" }}><span>0.0</span></div>
                  <div className="rv-vchart-gridline" style={{ bottom: "33%" }}><span>0.15</span></div>
                  <div className="rv-vchart-gridline" style={{ bottom: "66%" }}><span>0.30</span></div>
                  <div className="rv-vchart-gridline" style={{ bottom: "100%" }}><span>{maxScore.toFixed(2)}</span></div>
                </div>
                <div className="rv-vchart-cols">
                  {dx.ranking.map((r) => {
                    const tier = r.rank <= 3 ? "top" : r.rank <= 10 ? "mid" : "low";
                    const heightPct = maxScore > 0 ? (r.score / maxScore) * 100 : 0;
                    return (
                      <div key={r.key} className={`rv-vcol rv-vcol-${tier}`} title={`${r.rank}. ${r.label} (${r.score.toFixed(2)})`}>
                        <div className="rv-vcol-score">{r.score.toFixed(2)}</div>
                        <div className="rv-vcol-bar-wrap">
                          <div
                            className="rv-vcol-bar"
                            style={{
                              height: `${heightPct}%`,
                              animationDelay: `${(r.rank - 1) * 0.03}s`,
                            }}
                          />
                        </div>
                        <div className="rv-vcol-rank">{String(r.rank).padStart(2, "0")}</div>
                        <div className="rv-vcol-key">{r.key}</div>
                      </div>
                    );
                  })}
                </div>
              </div>
              <div className="rv-vchart-legend">
                <span className="rv-vchart-legend-item"><i className="rv-legend-dot rv-legend-top" />Top 3 · 強く出た欲求</span>
                <span className="rv-vchart-legend-item"><i className="rv-legend-dot rv-legend-mid" />Mid · 補助的</span>
                <span className="rv-vchart-legend-item"><i className="rv-legend-dot rv-legend-low" />Low · 弱い</span>
              </div>
            </section>

            <section className="rv-card-block rv-insight">
              <div className="rv-block-tag">CORE INSIGHT · 核心</div>
              <p className="rv-hero-lead">{dx.insight.summary}</p>
              <p className="rv-hero-headline">
                「<em>{dx.insight.headline}</em>」
              </p>
              <div className="rv-hero-strongs rv-hero-strongs-row">
                {dx.topDesires.map((d, i) => (
                  <div key={d.key} className="rv-strong-chip">
                    <span className="rv-strong-rank">0{i + 1}</span>
                    <span>{d.label}</span>
                  </div>
                ))}
              </div>
            </section>

            <div className="rv-pair">
              <section className="rv-card-block rv-analysis">
                <div className="rv-block-tag">買う理由 · WHY YOU BUY</div>
                <p className="rv-analysis-body">{dx.analysis.body}</p>
              </section>

              <section className="rv-card-block rv-anti">
                <div className="rv-block-tag rv-block-tag-warn">刺さりにくい · ANTI-PATTERN</div>
                <ul className="rv-anti-list">
                  {dx.antiPatterns.items.map((it, i) => (
                    <li key={i} className="rv-anti-item">
                      <span className="rv-anti-x">×</span>
                      <span>{it}</span>
                    </li>
                  ))}
                </ul>
              </section>
            </div>

            <button className="rv-cta-next" onClick={goProducts}>
              {dx.products ? (
                <>
                  <span className="rv-cta-next-eyebrow">あなたに刺さる{dx.products.length}商品を見る</span>
                  <span className="rv-cta-next-row">
                    <span className="rv-cta-next-label">商品を見る</span>
                    <span className="rv-cta-next-arrow">→</span>
                  </span>
                </>
              ) : dx.productError ? (
                <>
                  <span className="rv-cta-next-eyebrow rv-cta-error">商品検索でエラーが発生しました</span>
                  <span className="rv-cta-next-row">
                    <span className="rv-cta-next-label">再試行する</span>
                    <span className="rv-cta-next-arrow">↻</span>
                  </span>
                </>
              ) : (
                <>
                  <span className="rv-cta-next-eyebrow">
                    楽天市場からリアルタイム検索中
                    {productSearchStart && <> · <ElapsedTimer startTime={productSearchStart} /></>}
                  </span>
                  <span className="rv-cta-next-row">
                    <span className="rv-cta-next-label">商品を探しています</span>
                    <span className="rv-cta-next-dots"><i></i><i></i><i></i></span>
                  </span>
                </>
              )}
            </button>
          </div>
        )}

        {page === "products" && (
          <div className="rv-page rv-page-products" key="products">
            <div className="rv-products-lead">
              <div className="rv-products-lead-eyebrow">FROM YOUR DIAGNOSIS · 解析結果より</div>
              <p className="rv-products-lead-text">
                「<em>{dx.insight.headline}</em>」<br />
                <span>—— その欲望に、これらが応えます。</span>
              </p>
            </div>

            {dx.products ? (
              <div className="rk-stack">
                {normalizeProductList(dx.products).map((p, i) => (
                  <RakutenProductCard
                    key={p.itemCode}
                    product={p}
                    rank={i + 1}
                    theme={theme}
                  />
                ))}
              </div>
            ) : dx.productError ? (
              <div className="rv-products-error">
                <div className="rv-products-error-icon">⚠</div>
                <p className="rv-products-error-text">商品検索中にエラーが発生しました</p>
                <p className="rv-products-error-detail">{dx.productError}</p>
                <button className="rv-products-error-retry" onClick={onReset}>もう一度最初から試す</button>
              </div>
            ) : (
              <div className="rv-products-loading">
                <div className="rv-products-loading-orb">
                  <div className="intro-orb-core" />
                  <div className="intro-orb-ring intro-orb-ring-1" style={{ animationDuration: "3s" }} />
                  <div className="intro-orb-ring intro-orb-ring-2" style={{ animationDuration: "4s" }} />
                </div>
                <p className="rv-products-loading-text">
                  楽天市場からあなたに刺さる商品を検索しています
                  <span className="rv-cta-next-dots"><i></i><i></i><i></i></span>
                </p>
                {productSearchStart && (
                  <div className="rv-products-loading-elapsed">
                    <span className="rv-products-loading-elapsed-label">検索経過時間</span>
                    <ElapsedTimer startTime={productSearchStart} />
                  </div>
                )}
                <p className="rv-products-loading-sub">診断結果をもとにリアルタイムで探索中です。しばらくお待ちください。</p>
              </div>
            )}

            <button className="rv-cta-back" onClick={goReport}>
              <span className="rv-cta-back-arrow">←</span>
              <span>解析結果に戻る</span>
            </button>
          </div>
        )}

        <p className="rv-note">※ {dx.meta.note}</p>

        <button className="rv-reset" onClick={onReset}>
          <span>もう一度試す</span>
          <span className="rv-reset-arrow">↻</span>
        </button>
      </div>
    </div>
  );
}

window.RevealScreen = RevealScreen;
