// Insurance Company / MGA journey
// 2 layout variants: 'inbox' (queue + detail) and 'workspace' (single-quote focus)

const InsurerJourney = ({ layout = 'inbox', onBack }) => {
  const [step, setStep] = useState(0);
  const [quoteId, setQuoteId] = useState('Q-29014');
  const [vesselId, setVesselId] = useState('');
  const [searching, setSearching] = useState(false);
  const [premium, setPremium] = useState('');
  const [binding, setBinding] = useState(false);
  const [bound, setBound] = useState(false);

  const steps = ['Quotes inbox', 'Match vessel & owner', 'Claims history', 'Duplicate cover check', 'Bind & record'];

  // Mock quote queue
  const QUOTES = [
    { id: 'Q-29014', applicant: 'Daniel & Sara Reston', vessel: 'Kestrel — Jeanneau Sun Odyssey 410', vesselId: 'KES-2019', source: 'API · GoSkippy retail flow', age: '4m', value: 240000, status: 'pending' },
    { id: 'Q-29013', applicant: 'Verity Cole', vessel: 'Tide Runner — Axopar 37', vesselId: 'TRN-2022', source: 'Portal · broker entry', age: '12m', value: 295000, status: 'pending' },
    { id: 'Q-29012', applicant: 'Salacia Holdings (BVI)', vessel: 'Salacia — Oyster 565', vesselId: 'SAL-2021', source: 'API · Marine wholesaler', age: '18m', value: 1450000, status: 'pending' },
    { id: 'Q-29011', applicant: 'Geoffrey Marlow', vessel: "Marlow's Pride — Westerly Konsort", vesselId: 'MLP-1989', source: 'Portal · direct', age: '47m', value: 22000, status: 'pending' },
    { id: 'Q-29010', applicant: 'Avalon Maritime Ltd', vessel: 'Solent Voyager — Princess V58', vesselId: 'SLV-2019', source: 'API · Premier broker', age: '1h', value: 845000, status: 'priced' },
  ];

  const selectedQuote = QUOTES.find(q => q.id === quoteId);
  const boat = BOATS.find(b => b.id === (vesselId || selectedQuote?.vesselId));

  const goMatch = (id) => {
    setQuoteId(id);
    const q = QUOTES.find(x => x.id === id);
    setVesselId(q.vesselId);
    setStep(1);
    setSearching(true);
    setTimeout(() => setSearching(false), 1400);
  };

  const goBind = () => {
    setBinding(true);
    setTimeout(() => { setBinding(false); setBound(true); setStep(5); }, 1500);
  };

  const reset = () => { setStep(0); setBound(false); setVesselId(''); setQuoteId('Q-29014'); setPremium(''); };

  // ----- Screen: Inbox -----
  const ScreenInbox = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: layout === 'workspace' ? '1fr' : '1fr 1.2fr', gap: 20 }}>
      <div className="card" style={{ overflow: 'hidden' }}>
        <CardHeader title="Pending quotes" sub="From API + portal · last 6 hours" icon="bell" right={<span className="pill pill-info">{QUOTES.filter(q => q.status === 'pending').length} new</span>} />
        <div>
          {QUOTES.map(q => {
            const qBoat = BOATS.find(b => b.id === q.vesselId);
            const isSel = quoteId === q.id;
            return (
              <div
                key={q.id}
                onClick={() => { setQuoteId(q.id); if (layout === 'workspace') goMatch(q.id); }}
                style={{
                  padding: '14px 18px', borderBottom: '1px solid var(--line)',
                  display: 'flex', alignItems: 'center', gap: 12,
                  cursor: 'pointer',
                  background: isSel ? 'var(--accent-soft)' : 'transparent',
                  borderLeft: isSel ? '3px solid var(--accent)' : '3px solid transparent',
                  transition: 'background .15s',
                }}
                onMouseEnter={(e) => { if (!isSel) e.currentTarget.style.background = 'var(--paper-2)'; }}
                onMouseLeave={(e) => { if (!isSel) e.currentTarget.style.background = 'transparent'; }}
              >
                <VesselThumb boat={qBoat} w={48} h={34} radius={5} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{q.id}</span>
                    <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>· {q.source}</span>
                  </div>
                  <div style={{ fontWeight: 500, fontSize: 13.5, marginTop: 1 }}>{q.applicant}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{q.vessel}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>{formatGBP(q.value)}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{q.age} ago</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {layout === 'inbox' ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {selectedQuote && (
            <div className="card">
              <CardHeader title={`Quote ${selectedQuote.id}`} sub={selectedQuote.source} icon="doc" right={<StatusPill state="info" label="Pending checks" />} />
              <div style={{ padding: 18 }}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                  <VesselThumb boat={boat} w={92} h={66} radius={8} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 16 }}>{boat.name}</div>
                    <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>{boat.make} {boat.model} · {boat.year}</div>
                    <div className="mono" style={{ color: 'var(--ink-3)', fontSize: 11.5, marginTop: 3 }}>{boat.hin}</div>
                  </div>
                </div>
                <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
                  <KVStack label="Applicant" value={selectedQuote.applicant} />
                  <KVStack label="Declared value" value={formatGBP(selectedQuote.value)} mono />
                  <KVStack label="Source" value={selectedQuote.source} />
                  <KVStack label="Cover requested" value="Comprehensive · UK & N. Europe" />
                </div>
              </div>
              <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>API call received {selectedQuote.age} ago — auto-routed to underwriter queue</span>
                <button className="btn btn-primary" onClick={() => goMatch(selectedQuote.id)}>
                  Run register checks<Icon name="arrowRight" color="white" />
                </button>
              </div>
            </div>
          )}
          <div className="card card-pad" style={{ background: 'var(--paper-2)', borderStyle: 'dashed' }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <div style={{ color: 'var(--accent)' }}><Icon name="api" size={18} /></div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 13.5 }}>API path (auto, no manual step)</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 4, lineHeight: 1.55 }}>
                  Your quote system calls <span className="mono" style={{ background: 'white', padding: '1px 5px', borderRadius: 3, border: '1px solid var(--line)' }}>POST /v1/checks/insurance</span> at quote.
                  We return the full register match, claims history, duplicate-policy flag, and a risk score —
                  inline in the underwriting workflow, no manual lookup. This portal view is the fallback.
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );

  // ----- Screen: Match -----
  const ScreenMatch = () => {
    if (searching) {
      return (
        <div className="fade-up card" style={{ padding: 48, textAlign: 'center' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 56, height: 56, borderRadius: 12, background: 'var(--accent-soft)', color: 'var(--accent)', marginBottom: 20 }}>
            <LoadRing size={22} />
          </div>
          <div style={{ fontSize: 18, fontWeight: 600 }}>Matching against the register…</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)', marginTop: 6 }}>HIN <span className="mono">{boat?.hin}</span> · owner reconciliation in progress</div>
        </div>
      );
    }
    if (!boat) return null;

    return (
      <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
        <div className="card">
          <CardHeader title="Vessel & owner match" sub="HIN + owner reconciliation across the register" icon="boat" right={<StatusPill state="clean" label="Matched" />} />
          <div style={{ padding: 18 }}>
            <div style={{ display: 'flex', gap: 16, marginBottom: 18 }}>
              <VesselThumb boat={boat} w={110} h={80} radius={8} />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 17, letterSpacing: '-0.01em' }}>{boat.name}</div>
                <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>{boat.make} {boat.model} · {boat.year} · {boat.type}</div>
                <div className="mono" style={{ color: 'var(--ink-3)', fontSize: 11.5, marginTop: 4 }}>{boat.hin} · {boat.reg}</div>
                <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                  <span className="pill pill-info" style={{ fontSize: 11 }}>{boat.length}</span>
                  <span className="pill" style={{ fontSize: 11 }}>{boat.moorings}</span>
                  <span className="pill" style={{ fontSize: 11 }}>{formatGBP(boat.value)}</span>
                </div>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
              <div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 6 }}>Registered owner</div>
                <KV label="Name" value={boat.owner.name} />
                <KV label="Kind" value={boat.owner.kind} />
                <KV label="Registered" value={formatDate(boat.owner.since)} />
                <KV label="Applicant match" value="Confirmed" status="clean" />
              </div>
              <div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 6 }}>Beneficial interest</div>
                {boat.finance ? (
                  <>
                    <KV label="Charge holder" value={boat.finance.lender} />
                    <KV label="Type" value="Marine mortgage" />
                    <KV label="Balance" value={formatGBP(boat.finance.balance)} mono />
                    <KV label="Term ends" value={boat.finance.term} />
                  </>
                ) : (
                  <div style={{ padding: 12, borderRadius: 6, background: 'var(--clean-soft)', color: 'var(--clean)', fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Icon name="check" /> No charges registered against this vessel.
                  </div>
                )}
              </div>
            </div>
          </div>
          <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between' }}>
            <button className="btn btn-ghost" onClick={() => setStep(0)}><Icon name="arrowLeft" />Back to inbox</button>
            <button className="btn btn-primary" onClick={() => setStep(2)}>Claims history<Icon name="arrowRight" color="white" /></button>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="card card-pad">
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 500, marginBottom: 10 }}>Risk score (provisional)</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <div style={{ fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em' }}>{boat.state === 'alert' ? 'D' : boat.state === 'flag' ? 'B' : 'A'}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{boat.state === 'alert' ? 'Declined risk' : boat.state === 'flag' ? 'Refer to senior' : 'Standard book'}</div>
            </div>
            <div style={{ marginTop: 12, height: 6, background: 'var(--line)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{
                height: '100%', width: boat.state === 'alert' ? '85%' : boat.state === 'flag' ? '55%' : '22%',
                background: boat.state === 'alert' ? 'var(--alert)' : boat.state === 'flag' ? 'var(--flag)' : 'var(--clean)',
              }} />
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 8 }}>Composite score across vessel, owner, claims, market signal.</div>
          </div>
          <div className="card card-pad">
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 500, marginBottom: 10 }}>Cross-market signals</div>
            <KV label="Prior insurers" value="2 historical" />
            <KV label="Hull identity" value="Consistent" status="clean" />
            <KV label="Owner — companies" value="1 directorship" />
            <KV label="Fraud watch" value={boat.state === 'alert' ? 'Match' : 'No match'} status={boat.state === 'alert' ? 'alert' : 'clean'} />
          </div>
        </div>
      </div>
    );
  };

  // ----- Screen: Claims history -----
  const ScreenClaims = () => {
    if (!boat) return null;
    return (
      <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16 }}>
        <div className="card">
          <CardHeader title="Cross-market claims history" sub="All participating insurers · vessel & owner" icon="history" right={<StatusPill state={boat.claims.length === 0 ? 'clean' : 'info'} label={`${boat.claims.length} claim${boat.claims.length !== 1 ? 's' : ''}`} />} />
          {boat.claims.length === 0 ? (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13.5 }}>
              <Icon name="check" color="var(--clean)" /> No claims recorded against this vessel or owner across the register.
            </div>
          ) : (
            <table className="data-table">
              <thead><tr><th>Date</th><th>Insurer</th><th>Loss type</th><th>Settlement</th><th>Status</th></tr></thead>
              <tbody>
                {boat.claims.map((c, i) => (
                  <tr key={i}>
                    <td>{formatDate(c.date)}</td>
                    <td>{boat.insurance.insurer}</td>
                    <td>{c.type}</td>
                    <td className="mono">{c.settled ? formatGBP(c.settled) : '—'}</td>
                    <td><StatusPill state={c.status === 'Open' ? 'alert' : 'neutral'} label={c.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
        <div className="card">
          <CardHeader title="Owner — prior policies" sub="History across all participating insurers" icon="user" />
          <table className="data-table">
            <thead><tr><th>Years</th><th>Insurer</th><th>Vessel</th><th>Claims</th></tr></thead>
            <tbody>
              <tr><td>2020 – 2022</td><td>GJW Direct</td><td>Prior vessel — Hanse 388</td><td>0</td></tr>
              <tr><td>2022 – 2024</td><td>{boat.insurance.insurer}</td><td>{boat.name}</td><td>{boat.claims.length}</td></tr>
              <tr><td>2024 – pres.</td><td>{boat.insurance.insurer}</td><td>{boat.name}</td><td>0</td></tr>
            </tbody>
          </table>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={() => setStep(1)}><Icon name="arrowLeft" />Back</button>
          <button className="btn btn-primary" onClick={() => setStep(3)}>Duplicate cover check<Icon name="arrowRight" color="white" /></button>
        </div>
      </div>
    );
  };

  // ----- Screen: Duplicate cover -----
  const ScreenDuplicate = () => {
    if (!boat) return null;
    const dup = boat.duplicateInsurance;
    return (
      <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16 }}>
        {dup ? (
          <>
            <FlagCard flag={{ severity: 'flag', summary: 'Active policy already registered against this vessel', detail: `${dup.insurer} (${dup.policy}) bound ${formatDate(dup.bound)}, in force to ${formatDate(dup.expires)}. Issuing a second policy will trigger an over-insurance flag.` }} />
            <div className="card">
              <CardHeader title="Existing active policy" icon="shield" right={<StatusPill state="flag" label="Active duplicate" />} />
              <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
                <KVStack label="Insurer" value={dup.insurer} />
                <KVStack label="Policy" value={dup.policy} mono />
                <KVStack label="Bound" value={formatDate(dup.bound)} />
                <KVStack label="Expires" value={formatDate(dup.expires)} />
              </div>
              <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', background: 'var(--paper-2)', fontSize: 12.5, color: 'var(--ink-2)' }}>
                <strong style={{ color: 'var(--ink)' }}>Underwriter note: </strong>
                contact applicant — confirm whether existing policy is being cancelled before binding. Issuing now will create cross-market conflict.
              </div>
            </div>
          </>
        ) : (
          <div className="card" style={{ background: 'var(--clean-soft)', borderColor: 'oklch(0.85 0.07 165)' }}>
            <div style={{ padding: 22, display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--clean)' }}>
                <Icon name="check" size={20} strokeWidth={2.2} />
              </div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 15 }}>No active duplicate cover found</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 2 }}>Most recent policy on file expired {formatDate(boat.insurance.expires)} — no overlap risk.</div>
              </div>
            </div>
          </div>
        )}
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={() => setStep(2)}><Icon name="arrowLeft" />Back</button>
          <div style={{ display: 'flex', gap: 8 }}>
            {dup && <button className="btn btn-secondary" onClick={reset}>Refer back to applicant</button>}
            <button className="btn btn-primary" onClick={() => setStep(4)}>Underwrite & price<Icon name="arrowRight" color="white" /></button>
          </div>
        </div>
      </div>
    );
  };

  // ----- Screen: Bind -----
  const ScreenBind = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 20 }}>
      <div className="card">
        <CardHeader title="Underwrite & bind" sub={`Quote ${quoteId} · ${boat?.name}`} icon="pound" />
        <div style={{ padding: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <KVStack label="Sum insured" value={formatGBP(boat?.value || 0)} mono />
          <KVStack label="Cover" value="Comprehensive · UK & N. Europe" />
          <div>
            <label className="input-label">Annual premium (gross)</label>
            <input className="input mono" placeholder="£" value={premium ? '£' + Number(premium).toLocaleString('en-GB') : ''} onChange={(e) => setPremium(e.target.value.replace(/[^0-9]/g, ''))} />
          </div>
          <div>
            <label className="input-label">Excess</label>
            <select className="select"><option>£1,000 standard</option><option>£2,500 reduced premium</option><option>£500 enhanced</option></select>
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <label className="input-label">Endorsements</label>
            <textarea className="input" rows="2" defaultValue="Beneficial interest noted (Coastline Capital). Cruising limits per schedule. Single-handed sailing excluded over 100nm offshore."></textarea>
          </div>
        </div>
        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>On bind, policy will be registered cross-market for duplicate detection.</span>
          <button className="btn btn-primary" onClick={goBind} disabled={binding || !premium}>
            {binding ? <><LoadRing /> Binding…</> : <>Bind & register<Icon name="check" color="white" /></>}
          </button>
        </div>
      </div>
      <div className="card card-pad">
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 500, marginBottom: 10 }}>Outcomes</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            'Cross-market claims visibility',
            'Duplicate cover detection live',
            'FCA Consumer Duty satisfied',
            'Beneficial interest noted',
            'Lapse alerts auto-enabled',
          ].map((t, i) => (
            <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 13 }}>
              <Icon name="check" color="var(--clean)" /> {t}
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  // ----- Screen: Done -----
  const ScreenDone = () => (
    <div className="fade-up" style={{ maxWidth: 720, margin: '0 auto' }}>
      <div className="card">
        <div style={{ padding: 28, background: 'linear-gradient(180deg, var(--clean-soft), white)', borderBottom: '1px solid var(--line)', textAlign: 'center' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 56, height: 56, borderRadius: 14, background: 'var(--clean)', color: 'white', marginBottom: 14 }}>
            <Icon name="shield" size={26} strokeWidth={2.2} color="white" />
          </div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>Policy bound & registered</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-2)', marginTop: 4 }}>Haven Knox-Johnston · {boat?.name} · annual premium {premium ? formatGBP(Number(premium)) : '—'}</div>
        </div>
        <div style={{ padding: 22, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
          <KVStack label="Policy reference" value={'HKJ-2026-' + Math.floor(10000 + Math.random() * 89999)} mono />
          <KVStack label="Bound" value={new Date().toLocaleString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })} />
          <KVStack label="Vessel" value={`${boat?.name} (${boat?.hin})`} />
          <KVStack label="Insured" value={selectedQuote?.applicant} />
        </div>
        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-secondary" onClick={reset}><Icon name="arrowLeft" />Back to inbox</button>
          <button className="btn btn-primary"><Icon name="download" color="white" />Send schedule</button>
        </div>
      </div>
    </div>
  );

  return (
    <PersonaShell
      persona={PERSONAS.find(p => p.id === 'insurer')}
      steps={steps}
      currentStep={step}
      onStep={(i) => setStep(i)}
      onBack={onBack}
      hint="Try Kestrel (duplicate cover) · Solent Voyager (clean) · Black Mamba (stolen)"
    >
      {step === 0 && ScreenInbox()}
      {step === 1 && ScreenMatch()}
      {step === 2 && ScreenClaims()}
      {step === 3 && ScreenDuplicate()}
      {step === 4 && ScreenBind()}
      {step === 5 && ScreenDone()}
    </PersonaShell>
  );
};

Object.assign(window, { InsurerJourney });
