// screens.jsx — individual screens for the PO onboarding flow
const { useState: uS, useEffect: uE, useRef: uR, useMemo: uM } = React;

// ════════════════════════════════════════════════════════════════
// SCREEN 1: ACTIVATION LANDING (lemon hero)
// ════════════════════════════════════════════════════════════════
const ActivationScreen = ({ heroColor, partnerName, cobrand, onAdvance }) => {
  const bg = { lemon: "var(--helm-lemon)", green: "var(--helm-dark-green)", ecru: "var(--helm-ecru)" }[heroColor];
  const fg = heroColor === "green" ? "var(--helm-white)" : "var(--helm-dark-green)";

  return (
    <main style={{ flex: 1, position: "relative", background: bg, overflow: "hidden", color: fg }}>
      {/* Decorative star pattern */}
      <div style={{
        position: "absolute", inset: 0, opacity: heroColor === "green" ? 0.08 : 0.18,
        backgroundImage: `url(assets/brand/helm-star.svg)`,
        backgroundSize: 72, backgroundPosition: "120% 100%", backgroundRepeat: "no-repeat",
        transform: "translate(120px, 80px) scale(8)",
        pointerEvents: "none",
      }} />
      {/* Curved swooping band */}
      <svg viewBox="0 0 800 600" preserveAspectRatio="none"
        style={{ position: "absolute", left: 0, bottom: 0, width: "70%", height: "70%", pointerEvents: "none" }}>
        <path d="M -20 580 Q 200 380 400 420 T 820 280 L 820 620 L -20 620 Z"
          fill={heroColor === "green" ? "rgba(247,247,117,0.12)" : "rgba(0,29,0,0.06)"} />
        <path d="M -20 600 Q 240 460 460 480 T 820 360 L 820 620 L -20 620 Z"
          fill={heroColor === "green" ? "rgba(198,179,235,0.18)" : "rgba(0,29,0,0.04)"} />
      </svg>

      <div style={{
        position: "relative", maxWidth: 760, padding: "72px 56px", height: "100%",
        display: "flex", flexDirection: "column", justifyContent: "center", boxSizing: "border-box",
      }}>
        <div style={{
          fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 500,
          textTransform: "uppercase", letterSpacing: "0.08em", opacity: 0.7, marginBottom: 16,
        }}>
          {cobrand ? `${partnerName} × Helm — Welcome` : "Welcome to Helm"}
        </div>
        <h1 style={{
          fontFamily: "var(--font-serif)", fontSize: 64, lineHeight: "68px",
          fontWeight: 600, letterSpacing: "-0.015em", margin: 0, color: fg,
          textWrap: "balance",
        }}>
          Chart your future<br/>so you can guide&nbsp;theirs.
        </h1>
        <p style={{
          fontFamily: "var(--font-sans)", fontSize: 20, lineHeight: "30px",
          fontWeight: 400, marginTop: 28, marginBottom: 0, maxWidth: 580,
          opacity: 0.85, textWrap: "pretty",
        }}>
          Helm is the relationship layer for life insurance — a place to gather your policies,
          understand what they actually do, and carry your guidance forward for the people you love.
        </p>

        <div style={{ display: "flex", gap: 14, marginTop: 44 }}>
          <Button variant={heroColor === "green" ? "lemon" : "primary"} onClick={onAdvance}>
            Add my policies →
          </Button>
        </div>

        <div style={{
          marginTop: 56, display: "flex", gap: 28, alignItems: "center",
          fontFamily: "var(--font-sans)", fontSize: 13, opacity: 0.65,
        }}>
          <span>Bank-level encryption</span>
          <span style={{ width: 4, height: 4, borderRadius: "50%", background: fg }}/>
          <span>SOC 2 Type II</span>
          <span style={{ width: 4, height: 4, borderRadius: "50%", background: fg }}/>
          <span>Your data, never sold</span>
        </div>
      </div>
    </main>
  );
};

// ════════════════════════════════════════════════════════════════
// SCREEN 2: UPLOAD POLICIES (drag-drop + browse)
// ════════════════════════════════════════════════════════════════
const SAMPLE_POLICY_FILES = [
  { name: "BannerLife_Term30_Policy.pdf", size: "1.2 MB", carrier: "Banner Life",
    text: `BANNER LIFE INSURANCE COMPANY — TERM LIFE POLICY
Policyholder: Suzie Garcia
Policy Number: 8675303202
Coverage Type: 30-Year Term Life
Face Amount: $500,000
Annual Premium: $612.00 (level for 30 years)
Issue Date: March 14, 2022
Expiration Date: March 14, 2052
Beneficiaries: John Garcia (spouse, 60%), Sarah Garcia (daughter, 40%)
Riders: Accelerated Death Benefit, Waiver of Premium for Disability, Convertibility to Permanent
Premium Mode: Annual
Underwriting Class: Preferred Plus Non-Tobacco`
  },
  { name: "NYLife_GroupLife_Certificate.pdf", size: "846 KB", carrier: "New York Life",
    text: `NEW YORK LIFE — GROUP TERM LIFE CERTIFICATE
Certificate Holder: Suzie Garcia
Group Policy: Aurora Health Systems Employer Plan
Certificate Number: 3032028675
Coverage Type: Group Term Life (Employer-Provided)
Face Amount: $200,000 (2x annual salary)
Premium: Paid by employer
Effective Date: January 1, 2023
Termination: Coverage ends upon termination of employment
Beneficiaries: John Garcia (spouse, 100%)
Portability: Conversion to individual policy available within 31 days of separation
Notes: Coverage reduces 35% at age 65, additional 15% at age 70`
  },
];

// Heuristic: sniff a carrier name from the first bit of policy text.
const KNOWN_CARRIERS = [
  "Banner Life", "New York Life", "Northwestern Mutual", "MassMutual",
  "Prudential", "MetLife", "John Hancock", "Lincoln Financial", "Pacific Life",
  "Guardian", "Transamerica", "AIG", "Mutual of Omaha", "State Farm",
  "Allstate", "Nationwide", "Principal", "Symetra", "Protective", "Haven Life",
  "Ladder", "Bestow", "Ethos", "Legal & General", "Securian", "Minnesota Life",
  "Penn Mutual", "Ameritas", "USAA", "Voya", "Brighthouse", "Sun Life",
];
function sniffCarrier(text) {
  if (!text) return "Unknown carrier";
  const head = text.slice(0, 4000);
  for (const c of KNOWN_CARRIERS) {
    const re = new RegExp(c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
    if (re.test(head)) return c;
  }
  return "Unknown carrier";
}

const UploadScreen = ({ onAdvance, uploaded, setUploaded, density, onStepClick }) => {
  const [dragOver, setDragOver] = uS(false);
  const [parsing, setParsing] = uS(false);
  const [parseError, setParseError] = uS(null);
  const fileInputRef = uR(null);

  const drop = (which) => {
    if (uploaded.find(u => u.name === SAMPLE_POLICY_FILES[which].name)) return;
    setUploaded([...uploaded, SAMPLE_POLICY_FILES[which]]);
  };

  const ingestFiles = async (fileList) => {
    const files = Array.from(fileList || []);
    if (files.length === 0) return;
    setParseError(null);
    setParsing(true);
    const next = [];
    for (const f of files) {
      const isPdf = f.type === "application/pdf" || /\.pdf$/i.test(f.name);
      try {
        let text = "";
        if (isPdf) {
          text = await window.extractPdfText(f);
        } else {
          // Best-effort text read for .txt or unknown
          text = await f.text();
        }
        if (!text || text.trim().length < 40) {
          setParseError(`${f.name} looks empty or scanned. Helm needs a text-based PDF — try exporting from your carrier's site.`);
          continue;
        }
        next.push({
          name: f.name,
          size: window.formatBytes(f.size),
          carrier: sniffCarrier(text),
          text: text.slice(0, 60000), // cap for prompt safety
          real: true,
        });
      } catch (e) {
        console.warn("PDF parse failed", f.name, e);
        setParseError(`Couldn't read ${f.name}. Make sure it's a text-based PDF (not a photo or scan).`);
      }
    }
    setParsing(false);
    if (next.length > 0) {
      setUploaded([...uploaded, ...next]);
    }
  };

  const onDrop = (e) => {
    e.preventDefault(); setDragOver(false);
    if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      ingestFiles(e.dataTransfer.files);
    }
  };
  const onPick = (e) => {
    ingestFiles(e.target.files);
    e.target.value = ""; // allow re-selecting same file
  };
  const pad = density === "compact" ? "32px 56px" : "56px 64px";

  return (
    <main style={{ flex: 1, padding: pad, background: "var(--helm-white)", overflow: "auto" }}>
      <div style={{ maxWidth: 720 }}>
        <StepBreadcrumb steps={["Add policies", "Review", "Coverage map"]} current={0} onStepClick={onStepClick} />
        <h1 style={{ fontFamily: "var(--font-serif)", fontSize: 48, lineHeight: "52px", fontWeight: 600,
          letterSpacing: "-0.015em", margin: "32px 0 12px" }}>
          Bring your policies into Helm.
        </h1>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 18, lineHeight: "28px",
          margin: 0, opacity: 0.8, maxWidth: 580 }}>
          Drag in any life insurance policy — declarations page, certificate, or summary.
          We'll read it and pull out the parts that matter.
        </p>

        {/* Drop zone */}
        <input ref={fileInputRef} type="file" accept="application/pdf,.pdf"
          multiple style={{ display: "none" }} onChange={onPick} />
        <div
          onDragOver={e => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={onDrop}
          onClick={() => !parsing && fileInputRef.current && fileInputRef.current.click()}
          style={{
            marginTop: 36, padding: "48px 32px",
            border: `2px dashed ${dragOver ? "var(--helm-chartreuse-2)" : "var(--helm-dark-green)"}`,
            borderRadius: 16,
            background: dragOver ? "rgba(141,153,51,0.08)" : "var(--helm-ecru)",
            textAlign: "center", cursor: parsing ? "wait" : "pointer", transition: "all .2s",
            opacity: parsing ? 0.7 : 1,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: "50%",
            background: "var(--helm-white)", border: "1px solid var(--helm-dark-green)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            marginBottom: 16,
          }}>
            {parsing ? (
              <svg className="helm-spin" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--helm-dark-green)" strokeWidth="2">
                <path d="M21 12a9 9 0 1 1-6.2-8.55" strokeLinecap="round"/>
              </svg>
            ) : (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--helm-dark-green)" strokeWidth="2">
                <path d="M12 5v14M5 12l7-7 7 7"/>
              </svg>
            )}
          </div>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 18, fontWeight: 600 }}>
            {parsing ? "Reading your PDF…" : "Drop your policy PDF here"}
          </div>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 14, opacity: 0.7, marginTop: 6 }}>
            {parsing ? "Extracting the text — this stays in your browser." : "…or click to browse. Real PDFs are sent to Helm's analyzer."}
          </div>
        </div>

        {parseError && (
          <div style={{
            marginTop: 14, padding: "12px 16px",
            background: "rgba(220, 80, 60, 0.08)",
            border: "1px solid rgba(220, 80, 60, 0.3)",
            borderRadius: 10, fontSize: 13, lineHeight: "20px",
            color: "var(--helm-dark-green)",
          }}>{parseError}</div>
        )}

        {/* Demo helpers — drop in mock policies for quick testing */}
        <div style={{ marginTop: 18, display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
          <span style={{ fontSize: 12, opacity: 0.6, marginRight: 4,
            textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600 }}>
            Or try a sample:
          </span>
          {SAMPLE_POLICY_FILES.map((f, i) => {
            const already = uploaded.find(u => u.name === f.name);
            return (
              <button key={i} disabled={!!already} onClick={() => drop(i)}
                style={{
                  padding: "6px 12px", fontSize: 13, fontWeight: 500,
                  fontFamily: "var(--font-sans)",
                  background: "var(--helm-white)",
                  border: "1px solid var(--helm-dark-ecru)",
                  borderRadius: 999, cursor: already ? "default" : "pointer",
                  color: "var(--helm-dark-green)",
                  opacity: already ? 0.4 : 1,
                }}>
                {already ? "✓ " : "+ "}{f.carrier}
              </button>
            );
          })}
        </div>

        {/* Uploaded files */}
        {uploaded.length > 0 && (
          <div style={{ marginTop: 36 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>
              Uploaded ({uploaded.length})
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {uploaded.map((f, i) => (
                <div key={i} style={{
                  display: "flex", alignItems: "center", gap: 16,
                  padding: "14px 18px", background: "var(--helm-white)",
                  border: "1px solid var(--helm-dark-ecru)", borderRadius: 12,
                }}>
                  <div style={{
                    width: 40, height: 48, borderRadius: 4, background: "var(--helm-ecru)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 10, fontWeight: 700, color: "var(--helm-dark-green)",
                  }}>PDF</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 500 }}>{f.name}</div>
                    <div style={{ fontSize: 13, opacity: 0.6 }}>{f.size} · {f.carrier}</div>
                  </div>
                  <button onClick={() => setUploaded(uploaded.filter((_, j) => j !== i))} style={{
                    background: "none", border: "none", cursor: "pointer", color: "var(--helm-dark-green)",
                    opacity: 0.5, fontSize: 14,
                  }}>Remove</button>
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{ marginTop: 40, display: "flex", gap: 12 }}>
          <Button variant="primary" disabled={uploaded.length === 0} onClick={onAdvance}>
            Analyze {uploaded.length} {uploaded.length === 1 ? "policy" : "policies"}
          </Button>
          <Button variant="ghost" onClick={onAdvance}>I'll do this later</Button>
        </div>
      </div>
    </main>
  );
};

// ════════════════════════════════════════════════════════════════
// SCREEN 3: AI SCANNING ANIMATION
// ════════════════════════════════════════════════════════════════
const ScanningScreen = ({ uploaded, animationLevel, onComplete, analyses }) => {
  // Steps cycle: Extracting → Matching → Summarizing
  const steps = ["Extracting policy details", "Matching against carrier database", "Summarizing coverage and purpose"];
  const [stepIdx, setStepIdx] = uS(0);
  const [progress, setProgress] = uS(0);

  uE(() => {
    // Progress: animationLevel sets total time
    const total = animationLevel === "subtle" ? 1500 : animationLevel === "cinematic" ? 8000 : 4500;
    const t0 = Date.now();
    const tick = () => {
      const elapsed = Date.now() - t0;
      const p = Math.min(1, elapsed / total);
      setProgress(p);
      setStepIdx(Math.min(steps.length - 1, Math.floor(p * steps.length)));
      if (p < 1) requestAnimationFrame(tick);
      else {
        // Wait for analyses to be ready, then advance
        const check = setInterval(() => {
          if (analyses.current && analyses.current.length === uploaded.length) {
            clearInterval(check);
            setTimeout(onComplete, 400);
          }
        }, 200);
      }
    };
    tick();
  }, []);

  const isCinematic = animationLevel === "cinematic";

  return (
    <main style={{
      flex: 1, position: "relative",
      background: isCinematic ? "var(--helm-dark-green)" : "var(--helm-white)",
      color: isCinematic ? "var(--helm-white)" : "var(--helm-dark-green)",
      overflow: "hidden",
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: 56,
    }}>
      {isCinematic && (
        <>
          <div className="orbit orbit1"/>
          <div className="orbit orbit2"/>
          <div className="orbit orbit3"/>
        </>
      )}

      {/* Big star with pulsing rings */}
      <div style={{ position: "relative", width: 180, height: 180, marginBottom: 36 }}>
        <div style={{
          position: "absolute", inset: 0, borderRadius: "50%",
          border: `1px solid ${isCinematic ? "rgba(247,247,117,0.3)" : "var(--helm-dark-ecru)"}`,
          animation: "helmRing 2s infinite ease-out",
        }}/>
        <div style={{
          position: "absolute", inset: 20, borderRadius: "50%",
          border: `1px solid ${isCinematic ? "rgba(247,247,117,0.4)" : "var(--helm-dark-ecru)"}`,
          animation: "helmRing 2s 0.5s infinite ease-out",
        }}/>
        <div style={{
          position: "absolute", inset: 40, borderRadius: "50%",
          background: isCinematic ? "rgba(247,247,117,0.08)" : "var(--helm-ecru)",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <StarIcon size={56} color={isCinematic ? "var(--helm-white)" : "var(--helm-dark-green)"}
            className="helm-spin-slow" />
        </div>
      </div>

      <div style={{
        fontSize: 12, fontWeight: 500, textTransform: "uppercase", letterSpacing: "0.12em",
        opacity: 0.6, marginBottom: 12,
      }}>Helm · {Math.round(progress * 100)}%</div>

      <h2 style={{ fontFamily: "var(--font-serif)", fontSize: 40, lineHeight: "44px",
        fontWeight: 600, letterSpacing: "-0.01em", margin: 0, textAlign: "center" }}>
        {steps[stepIdx]}…
      </h2>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: 16, lineHeight: "24px",
        opacity: 0.75, textAlign: "center", marginTop: 16, maxWidth: 540 }}>
        Reading {uploaded.length} {uploaded.length === 1 ? "document" : "documents"} —
        coverage type, beneficiaries, riders, and purpose. This stays on Helm.
      </p>

      {/* Step pips */}
      <div style={{ display: "flex", gap: 16, marginTop: 40 }}>
        {steps.map((s, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, opacity: i <= stepIdx ? 1 : 0.4 }}>
            <div style={{
              width: 22, height: 22, borderRadius: "50%",
              background: i < stepIdx ? "var(--helm-chartreuse-2)" :
                          i === stepIdx ? (isCinematic ? "var(--helm-lemon)" : "var(--helm-dark-green)") : "transparent",
              border: i > stepIdx ? `1px solid ${isCinematic ? "rgba(255,255,255,0.3)" : "var(--helm-dark-ecru)"}` : "none",
              color: i === stepIdx && isCinematic ? "var(--helm-dark-green)" : "var(--helm-white)",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 11, fontWeight: 700,
            }}>{i < stepIdx ? "✓" : i + 1}</div>
            <span style={{ fontSize: 13, fontWeight: 500 }}>{s.split(" ")[0]}</span>
          </div>
        ))}
      </div>
    </main>
  );
};

window.ActivationScreen = ActivationScreen;
window.UploadScreen = UploadScreen;
window.ScanningScreen = ScanningScreen;
window.SAMPLE_POLICY_FILES = SAMPLE_POLICY_FILES;
