/* BioReveal — Shen.AI bioscan step (feature-flagged).
 *
 * Activated when ?shen=1 is in the URL AND window.SHEN_API_KEY is set.
 * Drop the API key into bioreveal.html as window.SHEN_API_KEY before this
 * loads, then activate via ?shen=1 to A/B against the legacy homemade
 * scan. When validated, swap in main.jsx's stepDef without code change.
 *
 * Returns the same shape as the legacy bioscan but with a `shen` field
 * holding the full 30-metric vital-signs result for Claude to interpret.
 */

const ShenStep = ({ value, onChange }) => {
  const containerRef = React.useRef(null);
  const sdkRef = React.useRef(null);
  const [status, setStatus] = React.useState("idle"); // idle | loading | scanning | done | error
  const [errMsg, setErrMsg] = React.useState("");
  const [progress, setProgress] = React.useState(0);
  const [captured, setCaptured] = React.useState(!!value?.captured);

  const apiKey = (typeof window !== "undefined" && window.SHEN_API_KEY) || "";

  const start = async () => {
    setErrMsg("");
    setStatus("loading");
    if (!apiKey) {
      setErrMsg("SHEN_API_KEY not set — falling back to legacy bioscan.");
      setStatus("error");
      return;
    }
    try {
      // SDK loaded dynamically from Shen's CDN. Pinned version once we have
      // a contract; left as 'latest' for sandbox.
      const mod = await import("https://cdn.jsdelivr.net/npm/@shenai/sdk/+esm");
      const { CreateSDK } = mod;
      const sdk = await CreateSDK({}, { onRuntimeInitialized: () => {} });
      sdkRef.current = sdk;
      await sdk.initialize(apiKey, "", {
        onUserFlowFinished: handleFinished,
        onProgressUpdate: (p) => setProgress(Math.round((p || 0) * 100)),
      });
      sdk.attachToCanvas(containerRef.current);
      setStatus("scanning");
    } catch (err) {
      console.error("Shen init failed:", err);
      setErrMsg(err?.message || "Failed to load Shen.AI SDK");
      setStatus("error");
    }
  };

  const handleFinished = () => {
    try {
      const sdk = sdkRef.current;
      const results = sdk.getMeasurementResults();
      onChange({
        captured: true,
        provider: "shen",
        shen: results,
      });
      setCaptured(true);
      setStatus("done");
    } catch (err) {
      console.warn("Shen results unavailable:", err);
      setStatus("error");
      setErrMsg("Scan ran but no results returned. Try again or skip.");
    }
  };

  const skip = () => {
    try { sdkRef.current?.deinitialize?.(); } catch {}
    onChange({ skipped: true });
    setStatus("done");
    setCaptured(false);
  };

  React.useEffect(() => () => {
    try { sdkRef.current?.deinitialize?.(); } catch {}
  }, []);

  return (
    <>
      <div className="br-eyebrow">03 / 04 · Shen.AI bioscan · 60 sec</div>
      <h2 className="br-question">Camera on. Hold still. We read 30 signals.</h2>
      <p className="br-sub">Heart rate, HRV, breathing, blood pressure, stress, cardiac age, and 24 more — from one selfie video. Raw numbers stay private. You get the read.</p>

      <div className="br-selfie-frame" style={{ position: "relative", overflow: "hidden", background: "#0a0a0a", minHeight: 360 }}>
        <canvas ref={containerRef} style={{ width: "100%", height: "100%", display: status === "scanning" ? "block" : "none" }}/>
        <div className="br-corner tl"/><div className="br-corner tr"/><div className="br-corner bl"/><div className="br-corner br"/>
        {status === "idle" && (
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", color: "#888", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase" }}>
            Tap "Begin Shen scan"
          </div>
        )}
        {status === "loading" && (
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", color: "#bbb", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase" }}>
            Loading Shen.AI SDK…
          </div>
        )}
        {status === "scanning" && (
          <>
            <div className="br-selfie-stat" style={{ top: 16, left: 44 }}>● SHEN · {progress}%</div>
            <div className="br-selfie-stat" style={{ top: 16, right: 44 }}>30 SIGNALS</div>
            <div className="br-selfie-stat" style={{ bottom: 16, left: 44 }}>HOLD STILL</div>
          </>
        )}
        {status === "done" && captured && (
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(0,0,0,0.9), #000)", display: "grid", placeItems: "center", padding: 24, textAlign: "center", color: "#fff" }}>
            <div>
              <div style={{ fontSize: 56, marginBottom: 8 }}>✓</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.22em", opacity: 0.55 }}>SHEN BIOSCAN COMPLETE</div>
              <div style={{ marginTop: 14, fontSize: 12, opacity: 0.6, maxWidth: 320, lineHeight: 1.5 }}>The AI puts it all together on the next page.</div>
            </div>
          </div>
        )}
        {status === "error" && (
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", background: "#111", color: "#fff", padding: 24, textAlign: "center" }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.2em", opacity: 0.7, marginBottom: 12 }}>SHEN UNAVAILABLE</div>
              <div style={{ fontSize: 13, opacity: 0.85, maxWidth: 380, lineHeight: 1.5 }}>{errMsg || "Unknown error"}</div>
            </div>
          </div>
        )}
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
        {status === "idle" && (
          <>
            <button className="br-option" style={{ flex: 1, justifyContent: "center" }} onClick={start}>● Begin Shen scan</button>
            <button className="br-option" style={{ flex: 1, justifyContent: "center" }} onClick={skip}>Skip</button>
          </>
        )}
        {(status === "loading" || status === "scanning") && (
          <button className="br-option" style={{ flex: 1, justifyContent: "center", opacity: 0.6 }} disabled>Working…</button>
        )}
        {status === "done" && (
          <button className="br-option selected" style={{ flex: 1, justifyContent: "center" }}>{captured ? "✓ Shen bioscan saved" : "✓ Skipped"}</button>
        )}
        {status === "error" && (
          <>
            <button className="br-option" style={{ flex: 1, justifyContent: "center" }} onClick={start}>Try again</button>
            <button className="br-option" style={{ flex: 1, justifyContent: "center" }} onClick={skip}>Use legacy scan</button>
          </>
        )}
      </div>
    </>
  );
};

window.BR_STEPS = window.BR_STEPS || {};
window.BR_STEPS.ShenStep = ShenStep;
