/* BioReveal — Reveal page (v0.9 — analysis-first).
 *
 * Renders the AI's REAL analysis of the patient. No raw biomarker numbers
 * displayed — the AI interpreted them and wrote the read. Same render path
 * for both Claude and rules-engine output (they share schema).
 */

const PEPTIDE_PRICES = {
  "Sermorelin": 179, "NAD+": 189, "BPC-157": 149, "Glutathione": 119,
  "Ipamorelin": 169, "GHK-Cu": 159, "Selank": 139, "DSIP": 129,
  "B12 / MIC": 99, "CJC-1295": 169, "TB-500": 219, "Tesamorelin": 199,
  "Epitalon": 149, "Semax": 149, "PT-141": 119,
};

const StepAnalysis = ({ onStart, error, onRetry }) => {
  const lines = [
    "Reading what you said you want fixed",
    "Cross-checking your health background",
    "Reading the bioscan",
    "Listening to what you said",
    "Picking the right peptides for you",
    "Writing your personal read",
  ];
  const [i, setI] = React.useState(0);
  const startedRef = React.useRef(false);
  React.useEffect(() => { if (!startedRef.current) { startedRef.current = true; onStart(); } }, []);
  React.useEffect(() => {
    if (error || i >= lines.length) return;
    const t = setTimeout(() => setI(i + 1), 700);
    return () => clearTimeout(t);
  }, [i, error]);

  return (
    <div className="br-analysis">
      <div className="br-orb"/>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 28, letterSpacing: "-0.025em", textTransform: "uppercase" }}>
        {error ? "Synthesis paused" : "Writing your analysis"}
      </div>
      {!error && (
        <div className="br-analysis-lines">
          {lines.map((l, idx) => (
            <div key={l} className={"br-analysis-line " + (idx === i ? "active" : idx < i ? "done" : "")}>
              <span>{l}</span>
            </div>
          ))}
        </div>
      )}
      {error && (
        <div style={{ marginTop: 18, padding: 16, background: "var(--paper-2)", borderRadius: 8, fontSize: 13, color: "var(--muted)", maxWidth: 480, textAlign: "center" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", marginBottom: 6, color: "var(--ink)" }}>ERROR</div>
          {error}
          <div style={{ marginTop: 14 }}>
            <button className="btn btn-dark btn-sm" onClick={onRetry}>Retry →</button>
          </div>
        </div>
      )}
    </div>
  );
};

// Map peptide name → URL slug for deep-page links
const PEPTIDE_SLUG = {
  "Sermorelin": "sermorelin", "NAD+": "nad-plus", "BPC-157": "bpc-157",
  "Ipamorelin": "ipamorelin", "GHK-Cu": "ghk-cu", "Glutathione": "glutathione",
  "Selank": "selank", "DSIP": "dsip", "B12 / MIC": "b12-mic", "CJC-1295": "cjc-1295",
};

const Reveal = ({ profile, onRestart }) => {
  const { protocol } = profile;
  const peptides = (protocol.recommended_protocol || []).map(p => ({ ...p, price: PEPTIDE_PRICES[p.name] || 159 }));
  const total = peptides.reduce((s, p) => s + p.price, 0);
  const engine = protocol._meta?.engine || "fallback";
  const { MDReviewer, ComplianceStrip, Testimonials, PressStrip } = window.BR_TRUST || {};
  const { ChatSidekick } = window.BR_CHAT || {};

  // Split analysis paragraphs
  const analysisParas = (protocol.analysis || "").split(/\n\n+/).filter(Boolean);

  return (
    <div className="br-page">
      <Header active="bioreveal"/>

      {/* HERO — headline + engine tag */}
      <section className="br-reveal-hero">
        <div className="container">
          <div className="br-archetype-tag">★ YOUR PERSONAL READ</div>
          <h1 className="br-archetype-name">{protocol.stack_name}</h1>
          <p className="br-archetype-sub">{protocol.headline}</p>
        </div>
      </section>

      {/* THE ANALYSIS — the new headline section */}
      {analysisParas.length > 0 && (
        <section className="br-section" style={{ paddingTop: 40, paddingBottom: 40 }}>
          <div className="container" style={{ maxWidth: 720 }}>
            <div className="eyebrow" style={{ marginBottom: 18 }}>★ THE READ</div>
            {analysisParas.map((p, i) => (
              <p key={i} style={{ fontSize: 17, lineHeight: 1.65, color: "var(--ink)", marginBottom: 14 }}
                 dangerouslySetInnerHTML={{ __html: p.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>") }}/>
            ))}
          </div>
        </section>
      )}

      {/* PROTOCOL CARDS */}
      {peptides.length > 0 && (
        <section className="br-section" style={{ background: "var(--paper-2)", paddingTop: 56, paddingBottom: 56 }}>
          <div className="container">
            <div className="br-section-head">
              <div className="eyebrow">★ THE PROTOCOL</div>
              <h2>What we'd recommend.</h2>
              <p>{peptides.length} peptide{peptides.length > 1 ? "s" : ""}, sequenced for your goals + signals. A licensed clinician reviews before anything ships.</p>
            </div>
            <div className="br-stack-grid">
              {peptides.map((p, i) => (
                <div key={p.name} className="br-pep-card" style={{ animationDelay: (0.1 + i * 0.15) + "s" }}>
                  <div className="br-pep-shot">
                    <ProductShot product={p.name.replace(" / MIC","").replace(/\s+\(.+/,"")} chip={false}/>
                  </div>
                  <div className="br-pep-body">
                    <div>
                      <h3 className="br-pep-name">{p.name}</h3>
                      <div className="br-pep-tag">{p.mechanism_short}</div>
                    </div>
                    <p className="br-pep-reason">
                      <strong>★ Why for you</strong>
                      {p.match_reason}
                    </p>
                  </div>
                  <div className="br-mbl">
                    <div className="br-mbl-cell"><div className="label">Dose</div><div className="val">{p.dose}</div></div>
                    <div className="br-mbl-cell"><div className="label">Week 1</div><div className="val">{p.expected_week_1}</div></div>
                    <div className="br-mbl-cell"><div className="label">Week 12</div><div className="val">{p.expected_week_12}</div></div>
                  </div>
                  {(p.side_effects_likely?.length || p.contraindications?.length) ? (
                    <div style={{ padding: "10px 14px", borderTop: "1px solid var(--paper-3)", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.05em", color: "var(--muted)" }}>
                      {p.side_effects_likely?.length > 0 && <div>SIDE EFFECTS · {p.side_effects_likely.join(" · ")}</div>}
                      {p.contraindications?.length > 0 && <div style={{ marginTop: 4 }}>⚠ AVOID IF · {p.contraindications.join(" · ")}</div>}
                    </div>
                  ) : null}
                  <div className="br-pep-foot">
                    <div className="br-pep-price">${p.price}<small>/mo</small></div>
                    <a href={PEPTIDE_SLUG[p.name] ? `/peptides/${PEPTIDE_SLUG[p.name]}.html` : "/peptides/"} className="btn btn-sm btn-dark">Read more →</a>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* LIFESTYLE PLAYS */}
      {protocol.lifestyle_plays?.length > 0 && (
        <section className="br-section">
          <div className="container" style={{ maxWidth: 760 }}>
            <div className="br-section-head">
              <div className="eyebrow">★ FREE LEVERS</div>
              <h2>Lifestyle moves that compound the protocol.</h2>
              <p>These cost nothing and double the effect of every peptide we recommended.</p>
            </div>
            <div style={{ display: "grid", gap: 12 }}>
              {protocol.lifestyle_plays.map((l, i) => (
                <div key={i} style={{ background: "var(--paper-2)", borderRadius: 10, padding: "18px 20px" }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 6 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--muted)", flexShrink: 0 }}>{String(i + 1).padStart(2, "0")}</span>
                    <h3 style={{ fontSize: 18, fontWeight: 700, margin: 0 }}>{l.play}</h3>
                  </div>
                  <p style={{ fontSize: 14, color: "var(--muted)", margin: "4px 0 0 30px", lineHeight: 1.55 }}>{l.why}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* WHAT TO WATCH */}
      {protocol.what_to_watch?.length > 0 && (
        <section className="br-section" style={{ background: "var(--paper-2)" }}>
          <div className="container" style={{ maxWidth: 820 }}>
            <div className="br-section-head">
              <div className="eyebrow">★ HOW YOU'LL KNOW IT'S WORKING</div>
              <h2>Track these week-to-week.</h2>
            </div>
            <div style={{ display: "grid", gap: 10 }}>
              {protocol.what_to_watch.map((w, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr 1fr", gap: 12, padding: "16px 18px", background: "var(--paper)", borderRadius: 8, border: "1px solid var(--paper-3)" }}>
                  <div>
                    <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.16em", color: "var(--muted)", textTransform: "uppercase", marginBottom: 4 }}>Track</div>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>{w.signal}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.16em", color: "#10b981", textTransform: "uppercase", marginBottom: 4 }}>If working</div>
                    <div style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.5 }}>{w.if_improving}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.16em", color: "#ef4444", textTransform: "uppercase", marginBottom: 4 }}>If not</div>
                    <div style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.5 }}>{w.if_not}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* HONEST CAVEAT */}
      {protocol.if_im_being_honest && (
        <section className="br-section">
          <div className="container" style={{ maxWidth: 720 }}>
            <div style={{ background: "#1a1a1a", color: "#fff", borderRadius: 14, padding: "28px 32px" }}>
              <div className="eyebrow" style={{ color: "#888", marginBottom: 12 }}>★ IF I'M BEING HONEST</div>
              <p style={{ fontSize: 16, lineHeight: 1.65, margin: 0 }}>{protocol.if_im_being_honest}</p>
            </div>
          </div>
        </section>
      )}

      {/* MD REVIEW FLAGS */}
      {protocol.md_review_flags?.length > 0 && protocol.md_review_flags[0] !== "routine_review" && (
        <section className="br-section" style={{ paddingTop: 32, paddingBottom: 32 }}>
          <div className="container">
            <div className="eyebrow" style={{ marginBottom: 12 }}>★ MD REVIEW FLAGS</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {protocol.md_review_flags.map(f => (
                <span key={f} style={{ background: "var(--ink)", color: "var(--paper)", padding: "8px 14px", borderRadius: 999, fontSize: 12, fontFamily: "var(--font-mono)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
                  ⚑ {f.replace(/_/g, " ")}
                </span>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* TRUST: MD reviewer */}
      {MDReviewer && <MDReviewer/>}

      {/* TRUST: testimonials */}
      {Testimonials && <Testimonials/>}

      {/* TRUST: compliance + money-back */}
      {ComplianceStrip && <ComplianceStrip/>}

      {/* TRUST: press */}
      {PressStrip && <PressStrip/>}

      {/* FINAL CTA */}
      <section className="br-final-cta">
        <div className="container">
          <h2>Book your $0 MD consult.</h2>
          {peptides.length > 0 && (
            <div className="br-final-price">
              Estimated stack · monthly
              <strong>${total}<span style={{ fontSize: 18, fontWeight: 600, opacity: 0.7 }}>/mo</span></strong>
            </div>
          )}
          <div className="br-final-buttons">
            <a href="product.html" className="btn btn-dark btn-lg">Book my consult →</a>
            <a href="#" className="btn btn-ghost btn-lg">Email me the analysis</a>
          </div>
          <div className="br-disclaimer">
            {protocol.disclaimer || "DRAFT — pending licensed clinician review."}
          </div>
          <button onClick={onRestart} style={{ background: "none", border: "none", color: "var(--ink)", opacity: 0.55, marginTop: 24, fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", cursor: "pointer" }}>
            ↺ Re-do the BioScan
          </button>
        </div>
      </section>

      <Footer/>

      {/* AI Chat Sidekick — floating button + slide-in panel */}
      {ChatSidekick && <ChatSidekick profile={profile}/>}
    </div>
  );
};

Object.assign(window, { Reveal, StepAnalysis });
