// Stage 4: Transcript review + Stage 5: Form filling

// Highlight tokens in transcript that map to extracted fields
const TranscriptCard = ({ transcript, durationSec, highlights = [], onContinue, onReRecord }) => {
  // highlights: [{match: string, kind: "id"|"money"|"name"|"contact"}]
  let body = transcript;
  // Build regex-escaped pattern
  const highlightEl = (text) => {
    if (!highlights.length) return text;
    const all = [...text];
    const parts = [];
    let i = 0;
    const find = (s, from) => {
      let best = null;
      highlights.forEach(h => {
        const idx = s.toLowerCase().indexOf(h.match.toLowerCase(), from);
        if (idx !== -1 && (best === null || idx < best.idx)) best = { idx, len: h.match.length, kind: h.kind };
      });
      return best;
    };
    while (i < text.length) {
      const f = find(text, i);
      if (!f) { parts.push(text.slice(i)); break; }
      if (f.idx > i) parts.push(text.slice(i, f.idx));
      parts.push({ snippet: text.substr(f.idx, f.len), kind: f.kind });
      i = f.idx + f.len;
    }
    const kindStyle = (k) => {
      const map = {
        id:      { bg: V.purpleSubtle, fg: V.purple },
        money:   { bg: V.orangeSubtle, fg: V.orange },
        name:    { bg: "rgba(22,163,74,0.08)", fg: V.success },
        contact: { bg: "rgba(36,20,13,0.06)", fg: V.brown },
      };
      return map[k] || map.contact;
    };
    return parts.map((p, idx) => typeof p === "string" ? p :
      <span key={idx} style={{ background: kindStyle(p.kind).bg, color: kindStyle(p.kind).fg, padding: "1px 5px", borderRadius: V.radiusSm, fontWeight: V.fw.m, whiteSpace: "nowrap" }}>{p.snippet}</span>
    );
  };

  const fmt = (s) => `${String(Math.floor(s/60)).padStart(2,"0")}:${String(Math.floor(s%60)).padStart(2,"0")}`;

  return (
    <div style={{ maxWidth: 820, margin: "0 auto", padding: "40px 32px" }}>
      <div style={{ marginBottom: 28 }}>
        <Eyebrow style={{ marginBottom: 10 }}>Step 3 of 4 · Transcript</Eyebrow>
        <h2 style={{ fontFamily: V.font, fontSize: 28, fontWeight: V.fw.m, color: V.brown, margin: 0, lineHeight: 1.1, letterSpacing: "-0.015em" }}>
          Verify the transcript
        </h2>
        <p style={{ fontFamily: V.font, fontSize: 13, color: V.brownMid, marginTop: 8 }}>
          Highlighted tokens are candidates for extraction. Review for errors — once you confirm, we'll extract into the form.
        </p>
      </div>

      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ padding: "14px 22px", borderBottom: `1px solid ${V.borderLight}`, background: V.offWhite, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: V.radiusSm, background: V.orangeSubtle, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="volume" size={14} color={V.orange}/>
            </div>
            <div>
              <div style={{ fontFamily: V.font, fontSize: 13, fontWeight: V.fw.m, color: V.brown }}>client-call-2026-04-22.m4a</div>
              <div style={{ fontFamily: V.font, fontSize: 11, color: V.brownFaded, fontVariantNumeric: "tabular-nums" }}>
                {fmt(durationSec)} · English + Hindi · confidence 94%
              </div>
            </div>
          </div>
          <MiniPlayer duration={durationSec}/>
        </div>

        <div style={{ padding: "24px 28px" }}>
          <div style={{ fontFamily: V.font, fontSize: 14, color: V.brown, lineHeight: 1.7 }}>
            {highlightEl(body)}
          </div>
        </div>

        <div style={{ padding: "14px 22px", borderTop: `1px solid ${V.borderLight}`, background: V.offWhite, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, fontFamily: V.font, fontSize: 11, color: V.brownMid }}>
            <LegendDot color={V.purple}  label="IDs (PAN, Aadhaar, GST)"/>
            <LegendDot color={V.orange}  label="Amounts"/>
            <LegendDot color={V.success} label="Names"/>
          </div>
        </div>
      </Card>

      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 20 }}>
        <Button variant="outline" icon="refresh" onClick={onReRecord}>Re-record</Button>
        <Button icon="sparkles" iconRight="arrowRight" onClick={onContinue}>Extract into form</Button>
      </div>
    </div>
  );
};

const LegendDot = ({ color, label }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
    <span style={{ width: 8, height: 8, borderRadius: 2, background: color, opacity: 0.5 }}/>
    {label}
  </span>
);

// ── FORM STAGE ─────────────────────────────────────────────────────────
const FormStage = ({ formKind, fields, extracted, itr, transcript, durationSec, onSubmit, onBack }) => {
  const sections = formKind === "sep" ? SECTIONS_SEP : SECTIONS_SALARIED;
  const [values, setValues] = React.useState(() => {
    const v = {};
    fields.forEach(f => { v[f.key] = extracted[f.key]?.value ?? null; });
    return v;
  });
  const [itrState, setItrState] = React.useState(itr || null);
  const [revealIdx, setRevealIdx] = React.useState(0); // animation counter
  const [focusedKey, setFocusedKey] = React.useState(null);

  // Staggered reveal animation
  React.useEffect(() => {
    if (revealIdx >= fields.length) return;
    const t = setTimeout(() => setRevealIdx(r => r + 1), 35);
    return () => clearTimeout(t);
  }, [revealIdx, fields.length]);

  const update = (k, v) => setValues(prev => ({ ...prev, [k]: v }));

  const getFieldStatus = (f) => {
    const ex = extracted[f.key];
    const v = values[f.key];
    if (v === null || v === undefined || v === "") {
      return f.required ? "missing" : "empty";
    }
    if (ex?.status === "spelled") return "spelled";
    if (ex?.c !== null && ex?.c !== undefined && ex.c < 0.75) return "low";
    return "filled";
  };

  // Missing required fields summary
  const isMarried = values.marital_status === "Married";
  const missing = fields.filter(f => {
    if (!f.required && f.key !== "spouse_name") return false;
    if (f.key === "spouse_name" && !isMarried) return false;
    const v = values[f.key];
    return v === null || v === undefined || v === "";
  });

  const lowConfCount = fields.filter(f => {
    const ex = extracted[f.key];
    return ex?.value !== null && ex?.c !== null && ex?.c !== undefined && ex.c < 0.75;
  }).length;

  const totalRequired = fields.filter(f => f.required).length + (isMarried ? 1 : 0);
  const filledRequired = totalRequired - missing.length;

  const filledBySection = {};
  sections.forEach(s => {
    const secFields = fields.filter(f => f.section === s.id);
    const secReq = secFields.filter(f => f.required || (f.key === "spouse_name" && isMarried));
    const secFilled = secReq.filter(f => values[f.key] !== null && values[f.key] !== undefined && values[f.key] !== "");
    filledBySection[s.id] = { filled: secFilled.length, total: secReq.length, totalAll: secFields.length };
  });

  const avgConfidence = (() => {
    const scores = fields.map(f => extracted[f.key]?.c).filter(c => c !== null && c !== undefined);
    return scores.reduce((a, b) => a + b, 0) / scores.length;
  })();

  return (
    <div style={{ maxWidth: 1180, margin: "0 auto", padding: "32px 32px 80px" }}>
      {/* Extraction summary banner */}
      <Card pad={0} style={{ marginBottom: 24, overflow: "hidden", position: "relative" }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "radial-gradient(circle, rgba(255,86,49,0.18) 0.8px, transparent 0.8px)",
          backgroundSize: "20px 20px", opacity: 0.6,
        }}/>
        <div style={{ position: "relative", padding: "22px 28px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <div style={{ position: "relative", width: 48, height: 48 }}>
              <div style={{ position: "absolute", inset: 0, borderRadius: "50%", background: V.orangeSubtle, display: "flex", alignItems: "center", justifyContent: "center" }}>
                <Icon name="sparkles" size={20} color={V.orange}/>
              </div>
              <FocusCorners color={V.orange} inset={-3} size={7}/>
            </div>
            <div>
              <div style={{ fontFamily: V.font, fontSize: 11, fontWeight: V.fw.m, color: V.orange, textTransform: "uppercase", letterSpacing: "0.12em", marginBottom: 4 }}>
                Extraction complete
              </div>
              <div style={{ fontFamily: V.font, fontSize: 17, fontWeight: V.fw.m, color: V.brown, lineHeight: 1.2 }}>
                Pre-filled {fields.filter(f => values[f.key] !== null && values[f.key] !== "").length} of {fields.length} fields from {Math.floor(durationSec/60)}:{String(Math.floor(durationSec%60)).padStart(2,"0")} voice note
              </div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 22 }}>
            <Stat label="Required filled" value={`${filledRequired}/${totalRequired}`} kind={missing.length === 0 ? "success" : "warning"}/>
            <Stat label="Avg. confidence" value={`${Math.round(avgConfidence * 100)}%`} kind="info"/>
            <Stat label="Low confidence" value={lowConfCount} kind={lowConfCount > 0 ? "warning" : "neutral"}/>
          </div>
        </div>
      </Card>

      {/* Missing required warning */}
      {missing.length > 0 && (
        <div style={{
          background: V.dangerBg, border: `1px solid rgba(220,38,38,0.25)`,
          borderRadius: V.radius, padding: "14px 18px",
          display: "flex", alignItems: "flex-start", gap: 12, marginBottom: 24,
          animation: "v2f-slide 0.4s ease-out",
        }}>
          <Icon name="alert" size={16} color={V.danger} style={{ marginTop: 2 }}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: V.font, fontSize: 13, fontWeight: V.fw.m, color: V.danger, marginBottom: 4 }}>
              {missing.length} required {missing.length === 1 ? "field is" : "fields are"} missing
            </div>
            <div style={{ fontFamily: V.font, fontSize: 12, color: V.brown, lineHeight: 1.5 }}>
              {missing.slice(0, 6).map((f, i) => (
                <span key={f.key}>
                  <a onClick={() => { document.getElementById("fld-" + f.key)?.scrollIntoView({ block: "center", behavior: "smooth" }); setFocusedKey(f.key); setTimeout(() => setFocusedKey(null), 1500); }} style={{ color: V.danger, cursor: "pointer", textDecoration: "underline", textUnderlineOffset: 2 }}>
                    {f.label}
                  </a>
                  {i < Math.min(missing.length, 6) - 1 && <span style={{ color: V.brownFaded }}> · </span>}
                </span>
              ))}
              {missing.length > 6 && <span style={{ color: V.brownFaded }}> · +{missing.length - 6} more</span>}
            </div>
          </div>
        </div>
      )}

      {/* Two column: sidebar section nav + sections */}
      <div style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 32, alignItems: "flex-start" }}>
        <aside style={{ position: "sticky", top: 80 }}>
          <div style={{ fontFamily: V.font, fontSize: 10, fontWeight: V.fw.m, color: V.brownFaded, textTransform: "uppercase", letterSpacing: "0.12em", marginBottom: 10, paddingLeft: 10 }}>Sections</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {sections.map(s => {
              const stat = filledBySection[s.id];
              const complete = stat.filled === stat.total;
              return (
                <a key={s.id} href={"#sec-" + s.id} onClick={(e) => { e.preventDefault(); document.getElementById("sec-" + s.id)?.scrollIntoView({ behavior: "smooth", block: "start" }); }}
                  style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 10px", borderRadius: V.radiusSm, fontFamily: V.font, fontSize: 12, color: V.brown, textDecoration: "none", cursor: "pointer", transition: "background 0.15s" }}
                  onMouseEnter={e => e.currentTarget.style.background = V.offWhite}
                  onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: complete ? V.success : stat.filled > 0 ? V.orange : V.borderMed, flexShrink: 0 }}/>
                  <span style={{ flex: 1 }}>{s.title}</span>
                  <span style={{ fontSize: 10, color: V.brownFaded, fontVariantNumeric: "tabular-nums" }}>{stat.filled}/{stat.total}</span>
                </a>
              );
            })}
          </div>
        </aside>

        <main style={{ minWidth: 0 }}>
          {sections.map(sec => {
            const secFields = fields.filter(f => f.section === sec.id);
            const stat = filledBySection[sec.id];
            return (
              <section key={sec.id} id={"sec-" + sec.id} style={{ marginBottom: 32, scrollMarginTop: 32 }}>
                <Card pad={28}>
                  <SectionHeader eyebrow={null} title={sec.title} subtitle={sec.subtitle} count={stat.filled} total={stat.total}/>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 18 }}>
                    {secFields.map((f, fi) => {
                      // Hide spouse if not married
                      if (f.conditional === "married" && !isMarried) return null;
                      const ex = extracted[f.key];
                      const status = getFieldStatus(f);
                      const globalIdx = fields.indexOf(f);
                      const shown = globalIdx < revealIdx;
                      const col = f.fullWidth ? "1 / -1" : "auto";
                      const isFocused = focusedKey === f.key;
                      const val = values[f.key];
                      const displayVal = (f.type === "number" && val !== null && val !== "" && f.monospace) ? val : val;
                      return (
                        <div key={f.key} id={"fld-" + f.key} style={{
                          gridColumn: col,
                          opacity: shown ? 1 : 0,
                          transform: shown ? "translateY(0)" : "translateY(6px)",
                          transition: "opacity 0.3s ease-out, transform 0.3s ease-out, box-shadow 0.3s",
                          borderRadius: V.radiusSm,
                          boxShadow: isFocused ? `0 0 0 3px rgba(255,86,49,0.25)` : "none",
                        }}>
                          <FormField
                            label={f.label}
                            value={displayVal}
                            onChange={(v) => update(f.key, v)}
                            placeholder={f.placeholder}
                            options={f.options}
                            icon={f.icon}
                            monospace={f.monospace}
                            type={f.type}
                            readOnly={f.readOnly}
                            required={f.required || (f.key === "spouse_name" && isMarried)}
                            confidence={ex?.c}
                            status={status}
                            note={ex?.note || (status === "missing" ? "Required — not captured in voice note" : null)}
                          />
                        </div>
                      );
                    })}
                    {/* ITR special block for SEP financials */}
                    {formKind === "sep" && sec.id === "financials" && itrState && (
                      <div style={{ gridColumn: "1 / -1", marginTop: 6 }}>
                        <ITRBlock itr={itrState} onChange={setItrState} revealed={revealIdx >= fields.length}/>
                      </div>
                    )}
                  </div>
                </Card>
              </section>
            );
          })}

          {/* Footer actions */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8, padding: "18px 0" }}>
            <Button variant="ghost" icon="arrowLeft" onClick={onBack}>Back to transcript</Button>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <div style={{ fontFamily: V.font, fontSize: 12, color: V.brownMid, marginRight: 6 }}>
                {missing.length === 0 ? (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: V.success }}>
                    <Icon name="checkCircle" size={13} color={V.success}/> All required fields filled
                  </span>
                ) : (
                  <span>{missing.length} required field{missing.length === 1 ? "" : "s"} remaining</span>
                )}
              </div>
              <Button variant="outline" icon="download">Save draft</Button>
              <Button icon="arrowRight" disabled={missing.length > 0} onClick={() => onSubmit(values)}>
                Submit application
              </Button>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
};

const Stat = ({ label, value, kind = "neutral" }) => {
  const colors = {
    success: V.success, warning: V.warning, info: V.purple, neutral: V.brown,
  };
  return (
    <div style={{ textAlign: "right", minWidth: 96 }}>
      <div style={{ fontFamily: V.font, fontSize: 10, color: V.brownFaded, textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 4 }}>{label}</div>
      <div style={{ fontFamily: V.font, fontSize: 20, fontWeight: V.fw.sb, color: colors[kind], fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>{value}</div>
    </div>
  );
};

const ITRBlock = ({ itr, onChange, revealed }) => (
  <div style={{
    background: V.offWhite, border: `1px dashed ${V.borderMed}`, borderRadius: V.radius,
    padding: 18,
    opacity: revealed ? 1 : 0, transition: "opacity 0.4s",
  }}>
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ width: 28, height: 28, borderRadius: V.radiusSm, background: V.purpleSubtle, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="file" size={13} color={V.purple}/>
        </div>
        <div style={{ fontFamily: V.font, fontSize: 13, fontWeight: V.fw.m, color: V.brown }}>ITR Filing History</div>
      </div>
      <ConfidenceBadge score={itr.c}/>
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "auto 1fr 1fr 1fr", gap: 16, alignItems: "center" }}>
      <label style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: V.font, fontSize: 12, color: V.brown }}>
        <input type="checkbox" checked={itr.filed} onChange={e => onChange({ ...itr, filed: e.target.checked })} style={{ accentColor: V.orange }}/>
        Filed
      </label>
      <FormField label="Years filed" value={itr.years_filed} type="number" onChange={v => onChange({ ...itr, years_filed: Number(v) })} monospace/>
      <FormField label="Last year income (₹)" value={itr.last_year_income} type="number" onChange={v => onChange({ ...itr, last_year_income: Number(v) })} monospace icon="coins"/>
      <FormField label="Prior year income (₹)" value={itr.prior_year_income} type="number" onChange={v => onChange({ ...itr, prior_year_income: Number(v) })} monospace icon="coins"/>
    </div>
  </div>
);

// Stage 6: Success
const SuccessStage = ({ values, formKind, onNew }) => {
  const applicant = values.full_name || "Applicant";
  const amount = values.loan_amount;
  const appId = "VEC-" + (formKind === "sep" ? "S" : "L") + "-2026-" + String(Math.floor(Math.random() * 900000) + 100000);
  return (
    <div style={{ maxWidth: 640, margin: "0 auto", padding: "80px 32px" }}>
      <Card pad={40} style={{ textAlign: "center", position: "relative", overflow: "hidden" }}>
        <div style={{
          position: "absolute", inset: 0,
          background: "radial-gradient(circle at 50% 0%, rgba(22,163,74,0.10) 0%, transparent 60%)",
        }}/>
        <div style={{ position: "relative" }}>
          <div style={{ width: 72, height: 72, borderRadius: "50%", background: V.successBg, display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 22, animation: "v2f-pop 0.5s ease-out" }}>
            <Icon name="checkCircle" size={34} color={V.success}/>
          </div>
          <h2 style={{ fontFamily: V.font, fontSize: 26, fontWeight: V.fw.m, color: V.brown, margin: 0, lineHeight: 1.1, letterSpacing: "-0.015em" }}>
            Application submitted
          </h2>
          <p style={{ fontFamily: V.font, fontSize: 13, color: V.brownMid, marginTop: 10, maxWidth: 400, margin: "10px auto 0" }}>
            {applicant}'s {formKind === "sep" ? "business loan" : "personal loan"} request has been queued for CIBIL pull and underwriting.
          </p>
          <div style={{ display: "flex", gap: 14, justifyContent: "center", marginTop: 28 }}>
            <div style={{ padding: "10px 16px", background: V.offWhite, borderRadius: V.radius, border: `1px solid ${V.borderLight}`, textAlign: "left" }}>
              <div style={{ fontFamily: V.font, fontSize: 10, color: V.brownFaded, textTransform: "uppercase", letterSpacing: "0.1em" }}>Application ID</div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13, fontWeight: V.fw.sb, color: V.brown, marginTop: 4, fontVariantNumeric: "tabular-nums" }}>{appId}</div>
            </div>
            <div style={{ padding: "10px 16px", background: V.offWhite, borderRadius: V.radius, border: `1px solid ${V.borderLight}`, textAlign: "left" }}>
              <div style={{ fontFamily: V.font, fontSize: 10, color: V.brownFaded, textTransform: "uppercase", letterSpacing: "0.1em" }}>Loan amount</div>
              <div style={{ fontFamily: V.font, fontSize: 13, fontWeight: V.fw.sb, color: V.brown, marginTop: 4, fontVariantNumeric: "tabular-nums" }}>₹ {formatINR(amount)}</div>
            </div>
            <div style={{ padding: "10px 16px", background: V.offWhite, borderRadius: V.radius, border: `1px solid ${V.borderLight}`, textAlign: "left" }}>
              <div style={{ fontFamily: V.font, fontSize: 10, color: V.brownFaded, textTransform: "uppercase", letterSpacing: "0.1em" }}>Est. decision</div>
              <div style={{ fontFamily: V.font, fontSize: 13, fontWeight: V.fw.sb, color: V.brown, marginTop: 4 }}>24–48 hrs</div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 32 }}>
            <Button variant="outline" icon="download">Download summary</Button>
            <Button icon="plus" onClick={onNew}>New application</Button>
          </div>
        </div>
      </Card>
    </div>
  );
};

Object.assign(window, { TranscriptCard, FormStage, SuccessStage });
