/* global React, Ic, Chip, ScoreBar, KPI, Panel, Av, AiBand */

function Onboarding() {
  const [sel, setSel] = React.useState(0);
  const apps = [
    { name: "RoadRunner Express LLC", mc: "MC-998772", state: "TX", stage: "REVIEW", score: 89, started: "2h ago", auth: "OK", insurance: "OK", w9: "OK", agreement: "PENDING", safer: "A", saferAlert: null, blocker: "MSA signature pending" },
    { name: "Sierra Pacific Trans",   mc: "MC-441881", state: "CA", stage: "AUTOAPPROVED", score: 96, started: "8h ago", auth: "OK", insurance: "OK", w9: "OK", agreement: "OK", safer: "A" },
    { name: "Cypress Cargo Inc",      mc: "MC-882211", state: "FL", stage: "FLAGGED", score: 52, started: "1d ago", auth: "OK", insurance: "EXPIRING 14D", w9: "OK", agreement: "PENDING", safer: "B", saferAlert: "OOS rate elevated", blocker: "Insurance + SAFER flag" },
];

  const cur = apps[sel];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Carrier Onboarding</div>
          <div className="page-sub">3 in queue · Avg time-to-approve 7min · Auto-approved 84%</div>
        </div>
        <div className="page-actions">
          <span className="chip accent"><span className="dot pulse" /> AI VETTING</span>
          <button className="btn ghost"><Ic.filter style={{ width: 12, height: 12 }} /> Status</button>
          <button className="btn primary"><Ic.plus style={{ width: 12, height: 12 }} /> Invite carrier</button>
        </div>
      </div>

      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="In Queue" value="3" delta="1" deltaKind="down" />
        <KPI label="Auto-approved (30d)" value="84%" delta="6pt" />
        <KPI label="Avg Time" value="7m 14s" delta="2m" deltaKind="down" />
        <KPI label="Blocked / Flagged" value="2" delta="0" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", minHeight: 540, marginTop: 16, borderTop: "1px solid var(--line)" }}>
        <div style={{ borderRight: "1px solid var(--line)" }}>
          {apps.map((a, i) => (
            <div key={a.mc} onClick={() => setSel(i)} style={{
              padding: 14, borderBottom: "1px solid var(--line)", cursor: "pointer",
              background: sel === i ? "var(--bg-sel)" : "transparent",
              borderLeft: sel === i ? "2px solid var(--accent)" : "2px solid transparent",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                <Chip kind={a.stage === "AUTOAPPROVED" ? "ok" : a.stage === "FLAGGED" ? "danger" : "warn"}>{a.stage}</Chip>
                <span className="mono dim" style={{ fontSize: 10, marginLeft: "auto" }}>{a.started}</span>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{a.name}</div>
              <div className="mono dim" style={{ fontSize: 10 }}>{a.mc} · {a.state}</div>
              <div style={{ marginTop: 10 }}>
                <ScoreBar value={a.score} color={a.score > 90 ? "var(--ok)" : a.score > 70 ? "var(--accent)" : "var(--warn)"} />
              </div>
            </div>
          ))}
        </div>

        <div style={{ padding: 20, overflowY: "auto" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
            <Av name={cur.name} />
            <div>
              <div style={{ fontSize: 18, fontWeight: 600 }}>{cur.name}</div>
              <div className="mono dim" style={{ fontSize: 11 }}>{cur.mc} · {cur.state} · started {cur.started}</div>
            </div>
            <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
              <button className="btn ghost">Reject</button>
              <button className="btn ghost">Request docs</button>
              <button className="btn primary"><Ic.check style={{ width: 12, height: 12 }} /> Approve</button>
            </div>
          </div>

          <AiBand
            confidence={cur.score}
            text={cur.stage === "AUTOAPPROVED"
              ? <>All checks passed. <b>Auto-approved</b> 38s ago. Ready to dispatch.</>
              : cur.stage === "FLAGGED"
              ? <><b>Flagged.</b> Insurance expires in 14 days. SAFER OOS rate {`>`} threshold. Recommend manual review.</>
              : <>Most checks passed. <b>Awaiting MSA signature</b> — email follow-up sent 2h ago.</>}
            actions={cur.stage !== "AUTOAPPROVED" && <>
              <button className="btn ghost sm">View report</button>
              <button className="btn primary sm">Override</button>
            </>}
          />

          {/* Steps grid */}
          <div className="grid cols-3" style={{ gap: 12, marginTop: 16 }}>
            <StepCard step="01" label="MC Authority" value={cur.auth} note="FMCSA Active · Common Authority" />
            <StepCard step="02" label="W9" value={cur.w9} note="EIN verified · IRS Pub 1635" />
            <StepCard step="03" label="Insurance COI" value={cur.insurance} note={cur.insurance === "OK" ? "$1M auto + $100k cargo · valid 2026" : "Auto liability expires 06/08"} />
            <StepCard step="04" label="SAFER / SMS" value={cur.safer} note={cur.saferAlert || "Driver OOS 0.4% · Vehicle OOS 6.2%"} flag={cur.saferAlert} />
            <StepCard step="05" label="MSA Agreement" value={cur.agreement} note={cur.agreement === "OK" ? "DocuSign envelope ENV-44918" : "Sent to ops@... 2h ago"} />
            <StepCard step="06" label="ACH / Factoring" value="OK" note="Direct ACH · Apex Capital factoring NOA" />
            <StepCard step="07" label="References" value="OK" note="3/3 positive · avg 4.7 rating" />
            <StepCard step="08" label="Watchlist" value="CLEAR" note="OFAC clear · no broker complaints" />
            <StepCard step="09" label="Equipment" value="OK" note="24 power units · 41 trailers · 53' Dry" />
          </div>

          {/* AI summary */}
          <Panel title="AI RISK SUMMARY" style={{ marginTop: 16 }}>
            <div style={{ fontSize: 13, lineHeight: 1.7 }}>
              {cur.stage === "AUTOAPPROVED" && (
                <>Sierra Pacific Trans is a strong match. Authority active 6.4 years, A safety, no OOS events in 24 months, $1M/$100k insurance current, A factoring partner. Recommended payment terms <b>QuickPay 1.5%</b> or NET 30. Suggested first-load max ${'$'}5,000 (auto-lift after 3 successful loads).</>
              )}
              {cur.stage === "REVIEW" && (
                <>RoadRunner Express looks solid. Authority active 2.1 years, A safety, insurance current. MSA signature outstanding — Keelway emailed ops@roadrunnerexpress.com 2h ago. Suggested action: auto-call carrier MSA owner at 14:30 if no response.</>
              )}
              {cur.stage === "FLAGGED" && (
                <>Cypress Cargo has multiple risks. Vehicle OOS rate 11.2% (industry median 6%). Insurance expires in 14 days — extension needed before any load. Two broker complaints in last 12 months. <b>Manual review required</b> before any auto-dispatch. Suggested: limit to single-load trial w/ extra detention safeguards if approved.</>
              )}
            </div>
          </Panel>
        </div>
      </div>
    </div>
  );
}

function StepCard({ step, label, value, note, flag }) {
  const ok = value === "OK" || value === "A" || value === "CLEAR";
  const warn = value === "PENDING" || value === "B" || (typeof value === "string" && value.includes("EXPIRING"));
  const danger = value === "FAIL" || value === "C" || flag;
  const color = ok ? "var(--ok)" : warn ? "var(--warn)" : danger ? "var(--danger)" : "var(--text-mid)";
  return (
    <div style={{ background: "var(--bg-1)", border: "1px solid var(--line)", borderRadius: 4, padding: 12, borderLeft: `2px solid ${color}` }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
        <span className="mono dim" style={{ fontSize: 10 }}>{step}</span>
        <span className="mono dim" style={{ fontSize: 10, letterSpacing: "0.12em" }}>{label.toUpperCase()}</span>
        <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 10, color, fontWeight: 600 }}>{value}</span>
      </div>
      <div style={{ fontSize: 11, color: "var(--text-mid)", lineHeight: 1.5 }}>{note}</div>
    </div>
  );
}

window.Onboarding = Onboarding;
