// Marina / Harbourmaster journey — includes OCR phone scan animation

const MarinaJourney = ({ onBack }) => {
  const [step, setStep] = useState(0);
  const [vesselId, setVesselId] = useState('');
  const [ocrPhase, setOcrPhase] = useState('idle'); // idle | scanning | extracting | done
  const [decision, setDecision] = useState(null); // 'granted' | 'declined' | null

  const steps = ['Berth application', 'Vessel verification', 'Insurance check', 'Ownership & fraud', 'Grant or decline'];
  const boat = BOATS.find(b => b.id === vesselId);

  // simulated incoming application (defaulted to Salacia for nice visuals)
  const application = {
    name: 'C. Whitworth',
    type: 'Visitor berth · 7 nights',
    arriving: '17 May 2026',
    length: 'Up to 18m',
  };

  const startOcr = (id) => {
    setVesselId(id);
    setOcrPhase('scanning');
    setStep(1);
    setTimeout(() => setOcrPhase('extracting'), 1300);
    setTimeout(() => setOcrPhase('done'), 2400);
  };

  const reset = () => { setStep(0); setVesselId(''); setOcrPhase('idle'); setDecision(null); };

  // ----- Berth Application -----
  const ScreenApplication = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
      <div className="card">
        <CardHeader title="Incoming berth application" sub="Walked in to berthing office · 2 minutes ago" icon="bell" right={<span className="pill pill-info">Awaiting verification</span>} />
        <div style={{ padding: 18 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            <KVStack label="Applicant (declared)" value={application.name} />
            <KVStack label="Vessel name (declared)" value="Salacia — Oyster 565" />
            <KVStack label="Berth requested" value={application.type} />
            <KVStack label="Arriving" value={application.arriving} />
            <KVStack label="Length declared" value="17.2 m" />
            <KVStack label="Berth assigned (prov.)" value="Pontoon E · slot 14" mono />
          </div>
          <div style={{ marginTop: 18, padding: 14, background: 'var(--paper-2)', borderRadius: 8, fontSize: 13, color: 'var(--ink-2)' }}>
            Standard procedure: scan the owner's paperwork (registration, insurance schedule) using the
            MarineCheck mobile app. Verification is real-time — typically under 30 seconds.
          </div>
        </div>
        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-ghost"><Icon name="x" />Decline politely</button>
          <button className="btn btn-primary" onClick={() => setStep(1)}>
            Begin verification<Icon name="scan" 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: 12 }}>Hamble Point · today</div>
        <Stat label="Berths occupied" value="184/206" sub="22 vacant" />
        <div style={{ height: 10 }} />
        <Stat label="Awaiting checks" value="3" sub="Avg. 26 sec to clear" />
        <div style={{ height: 10 }} />
        <Stat label="Lapse alerts (active stays)" value="2" sub="Insurance expired on stay" accent="var(--flag)" />
      </div>
    </div>
  );

  // ----- Verification (OCR) -----
  const ScreenVerify = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '420px 1fr', gap: 20 }}>
      {/* Phone frame */}
      <div className="card" style={{ background: 'var(--paper-2)', padding: 20 }}>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 500, marginBottom: 12, textAlign: 'center' }}>
          Marina staff phone · MarineCheck app
        </div>
        <div style={{
          background: '#0e1320', borderRadius: 32, padding: 10,
          margin: '0 auto', width: 320, height: 580, position: 'relative',
          boxShadow: '0 30px 60px -20px oklch(0.2 0.05 250 / 0.4), 0 8px 20px -10px oklch(0.2 0.05 250 / 0.2)',
        }}>
          {/* Screen */}
          <div style={{ background: 'white', borderRadius: 24, height: '100%', overflow: 'hidden', position: 'relative', display: 'flex', flexDirection: 'column' }}>
            {/* Status bar */}
            <div style={{ height: 28, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 24px', fontSize: 11, fontWeight: 600, color: 'var(--ink)' }}>
              <span>14:11</span>
              <span style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                <span style={{ width: 14, height: 8, border: '1px solid currentColor', borderRadius: 2, position: 'relative' }}>
                  <span style={{ position: 'absolute', inset: 1, background: 'currentColor', width: '70%', borderRadius: 1 }} />
                </span>
              </span>
            </div>
            {/* App header */}
            <div style={{ padding: '8px 16px 12px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="arrowLeft" size={18} color="var(--ink)" />
              <div style={{ flex: 1, textAlign: 'center', fontSize: 13, fontWeight: 600 }}>Scan paperwork</div>
              <div style={{ width: 18 }} />
            </div>

            {/* Camera viewfinder area */}
            <div style={{ flex: 1, position: 'relative', background: '#0a0d14', overflow: 'hidden' }}>
              {/* Faux document */}
              <div style={{
                position: 'absolute', top: 38, left: 24, right: 24, bottom: 38,
                background: '#f4f1e8',
                borderRadius: 4,
                padding: 14,
                fontSize: 7, lineHeight: 1.4, color: '#1a1a1a',
                fontFamily: 'Geist Mono, monospace',
                boxShadow: '0 10px 30px rgba(0,0,0,0.4)',
                transform: 'perspective(900px) rotateX(2deg)',
              }}>
                <div style={{ fontFamily: 'Geist, sans-serif', fontWeight: 700, fontSize: 10, marginBottom: 4 }}>PANTAENIUS UK LTD</div>
                <div style={{ fontSize: 6.5, marginBottom: 8, color: '#666' }}>Marine Insurance Schedule</div>
                <div style={{ borderTop: '0.5px solid #999', borderBottom: '0.5px solid #999', padding: '4px 0', marginBottom: 6 }}>
                  <div>Policy: PAN-2024-04018</div>
                  <div>Period: 15 Oct 2025 — 15 Oct 2026</div>
                </div>
                <div style={{ marginBottom: 3 }}>Insured: Salacia Holdings (BVI)</div>
                <div style={{ marginBottom: 3 }}>Vessel: SALACIA</div>
                <div style={{ marginBottom: 3 }}>Make/Model: Oyster 565 · 2021</div>
                <div style={{ marginBottom: 3 }}>HIN: GB-OYS565-21-0033</div>
                <div style={{ marginBottom: 3 }}>Registration: SSR 210504</div>
                <div style={{ marginBottom: 3 }}>Length: 17.2 m</div>
                <div style={{ marginBottom: 6 }}>Sum insured: £1,450,000</div>
                <div style={{ marginBottom: 3 }}>Cover: Comprehensive UK / Med</div>
                <div style={{ marginBottom: 3 }}>Excess: £2,500 standard</div>
                <div style={{ marginTop: 8, fontSize: 5.5, color: '#888', borderTop: '0.5px dashed #aaa', paddingTop: 4 }}>Signed: Pantaenius UK · Underwriter · 15.10.2025</div>
              </div>

              {/* Scan corners */}
              {[
                { top: 24, left: 14, borders: 'top left' },
                { top: 24, right: 14, borders: 'top right' },
                { bottom: 24, left: 14, borders: 'bottom left' },
                { bottom: 24, right: 14, borders: 'bottom right' },
              ].map((c, i) => (
                <div key={i} style={{
                  position: 'absolute',
                  width: 16, height: 16,
                  ...c,
                  borderTop: c.borders.includes('top') ? '2px solid #fff' : 'none',
                  borderBottom: c.borders.includes('bottom') ? '2px solid #fff' : 'none',
                  borderLeft: c.borders.includes('left') ? '2px solid #fff' : 'none',
                  borderRight: c.borders.includes('right') ? '2px solid #fff' : 'none',
                }} />
              ))}

              {/* Scanning bar */}
              {ocrPhase === 'scanning' && (
                <div style={{
                  position: 'absolute', left: 24, right: 24,
                  height: 2, background: 'oklch(0.7 0.18 240)',
                  boxShadow: '0 0 14px oklch(0.7 0.18 240), 0 0 30px oklch(0.7 0.18 240 / 0.6)',
                  animation: 'scanLine 1.3s ease-in-out infinite',
                  top: 40,
                }} />
              )}

              {/* Done overlay */}
              {ocrPhase === 'done' && (
                <div style={{ position: 'absolute', inset: 0, background: 'oklch(0.55 0.13 165 / 0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--clean)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name="check" size={28} color="white" strokeWidth={2.6} />
                  </div>
                </div>
              )}
            </div>

            {/* Bottom bar */}
            <div style={{ padding: '12px 16px', borderTop: '1px solid var(--line)', textAlign: 'center', fontSize: 11.5, fontWeight: 500, color: 'var(--ink-2)' }}>
              {ocrPhase === 'idle' && 'Position document inside the frame'}
              {ocrPhase === 'scanning' && <><LoadRing size={10} /> &nbsp; Scanning document…</>}
              {ocrPhase === 'extracting' && <><LoadRing size={10} /> &nbsp; Extracting fields…</>}
              {ocrPhase === 'done' && <span style={{ color: 'var(--clean)' }}>✓ Matched against the register</span>}
            </div>
          </div>
        </div>

        {ocrPhase === 'idle' && (
          <div style={{ marginTop: 14, textAlign: 'center' }}>
            <button className="btn btn-primary" onClick={() => startOcr('SAL-2021')}>Scan demo document</button>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 8 }}>or pick another vessel manually →</div>
          </div>
        )}
      </div>

      {/* Right side: live readout / fallback manual */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {ocrPhase === 'idle' ? (
          <div className="card">
            <CardHeader title="Manual entry" sub="If no paperwork available, enter the vessel manually" icon="search" />
            <div style={{ padding: 18 }}>
              <BoatSelect value={vesselId} onChange={(id) => startOcr(id)} />
              <div style={{ marginTop: 16, padding: 14, background: 'var(--paper-2)', borderRadius: 8, fontSize: 12.5, color: 'var(--ink-2)' }}>
                Once the vessel is identified, MarineCheck will check insurance, ownership, and stolen-vessel
                feeds in real time.
              </div>
            </div>
          </div>
        ) : (
          <div className="card">
            <CardHeader title="Extracted fields" sub="OCR result · matched to register" icon="scan" right={ocrPhase === 'done' ? <StatusPill state="clean" label="Matched" /> : <span className="pill"><LoadRing size={10} />&nbsp;Working</span>} />
            <div style={{ padding: 18 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                {[
                  ['Policy number', 'PAN-2024-04018', 'mono'],
                  ['Insurer', 'Pantaenius UK'],
                  ['Insured', 'Salacia Holdings (BVI)'],
                  ['Vessel', 'Salacia'],
                  ['HIN', 'GB-OYS565-21-0033', 'mono'],
                  ['Period', '15 Oct 2025 — 15 Oct 2026'],
                  ['Sum insured', '£1,450,000', 'mono'],
                  ['Cover', 'Comprehensive UK / Med'],
                ].map(([l, v, mono], i) => (
                  <div key={i} style={{
                    padding: '8px 10px',
                    background: ocrPhase === 'done' ? 'var(--clean-soft)' : 'var(--paper-2)',
                    borderRadius: 6,
                    border: '1px solid ' + (ocrPhase === 'done' ? 'oklch(0.85 0.07 165)' : 'var(--line)'),
                    opacity: ocrPhase === 'scanning' ? 0.4 : 1,
                    transition: 'all .3s',
                    animation: ocrPhase === 'extracting' ? `fadeUp .4s ${i * 0.08}s both` : 'none',
                  }}>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{l}</div>
                    <div className={mono ? 'mono' : ''} style={{ fontSize: 12.5, fontWeight: 500, marginTop: 2 }}>{v}</div>
                  </div>
                ))}
              </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)' }}>{ocrPhase === 'done' ? 'All fields match the register exactly.' : 'Working…'}</span>
              <button className="btn btn-primary" disabled={ocrPhase !== 'done'} onClick={() => setStep(2)} style={{ opacity: ocrPhase !== 'done' ? 0.5 : 1 }}>
                Insurance check<Icon name="arrowRight" color="white" />
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );

  // ----- Insurance confirmation -----
  const ScreenInsurance = () => {
    if (!boat) return null;
    const lapsed = boat.insurance.status !== 'Active';
    return (
      <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="card" style={{ background: lapsed ? 'var(--flag-soft)' : 'var(--clean-soft)', borderColor: lapsed ? 'oklch(0.85 0.1 60)' : 'oklch(0.85 0.07 165)' }}>
          <div style={{ padding: 22, display: 'flex', gap: 16, alignItems: 'center' }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', color: lapsed ? 'var(--flag)' : 'var(--clean)' }}>
              <Icon name={lapsed ? 'alert' : 'shield'} size={22} strokeWidth={2} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 17 }}>{lapsed ? 'Insurance is NOT currently in force' : 'Insurance in force'}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>
                {lapsed
                  ? `Last active policy: ${boat.insurance.insurer}. ${boat.insurance.status}.`
                  : `Policy ${boat.insurance.policy} with ${boat.insurance.insurer} valid to ${formatDate(boat.insurance.expires)}.`}
              </div>
            </div>
          </div>
        </div>
        <div className="card">
          <CardHeader title="Policy details" icon="shield" />
          <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
            <KVStack label="Insurer" value={boat.insurance.insurer} />
            <KVStack label="Policy" value={boat.insurance.policy} mono />
            <KVStack label="Expires" value={formatDate(boat.insurance.expires)} />
            <KVStack label="Status" value={<StatusPill state={lapsed ? 'flag' : 'clean'} label={boat.insurance.status} />} />
            <KVStack label="Sum insured" value={formatGBP(boat.value)} mono />
            <KVStack label="Cover area" value="UK / Med" />
            <KVStack label="3rd party" value="£3m" />
            <KVStack label="Berth licence" value={lapsed ? 'Will not satisfy' : 'Satisfies T&Cs'} />
          </div>
          {!lapsed && (
            <div style={{ padding: 14, borderTop: '1px solid var(--line)', background: 'var(--paper-2)', fontSize: 12.5, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="bell" /> Lapse alert auto-enabled for the duration of the stay. Berthing office will be notified if cover changes.
            </div>
          )}
        </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)}>Ownership & fraud<Icon name="arrowRight" color="white" /></button>
        </div>
      </div>
    );
  };

  // ----- Ownership & fraud -----
  const ScreenFraud = () => {
    if (!boat) return null;
    const stolen = boat.flags.find(f => f.kind === 'stolen');
    return (
      <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {stolen && <FlagCard flag={stolen} />}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <div className="card">
            <CardHeader title="Registered owner" icon="user" right={<StatusPill state="clean" label="Matches applicant" />} />
            <div style={{ padding: 18 }}>
              <KV label="Name" value={boat.owner.name} />
              <KV label="Kind" value={boat.owner.kind} />
              <KV label="Registered since" value={formatDate(boat.owner.since)} />
              <KV label="Identity" value="No disputes" status="clean" />
            </div>
          </div>
          <div className="card">
            <CardHeader title="Stolen / fraud feeds" icon="alert" right={<StatusPill state={stolen ? 'alert' : 'clean'} label={stolen ? 'Match' : 'No match'} />} />
            <div style={{ padding: 18 }}>
              <KV label="Police feed" value={stolen ? 'Match — Sussex Police' : 'No match'} status={stolen ? 'alert' : 'clean'} />
              <KV label="Insurer fraud watch" value="No match" status="clean" />
              <KV label="HIN integrity" value={stolen ? 'May be altered' : 'Consistent'} status={stolen ? 'alert' : 'clean'} />
              <KV label="Hull markings" value={stolen ? 'Mismatch suspected' : 'Verified'} status={stolen ? 'alert' : 'clean'} />
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={() => setStep(2)}><Icon name="arrowLeft" />Back</button>
          <button className="btn btn-primary" onClick={() => setStep(4)}>Decision<Icon name="arrowRight" color="white" /></button>
        </div>
      </div>
    );
  };

  // ----- Decision -----
  const ScreenDecision = () => {
    if (!boat) return null;
    const canGrant = boat.state !== 'alert' && boat.insurance.status === 'Active';
    return (
      <div className="fade-up" style={{ maxWidth: 680, margin: '0 auto' }}>
        <div className="card">
          <CardHeader title="Berth decision" sub={`${boat.name} · ${boat.hin}`} icon="map" />
          <div style={{ padding: 22 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 18 }}>
              <KVStack label="Insurance" value={<StatusPill state={boat.insurance.status === 'Active' ? 'clean' : 'flag'} label={boat.insurance.status} />} />
              <KVStack label="Ownership" value={<StatusPill state="clean" label="Matched" />} />
              <KVStack label="Stolen / fraud" value={<StatusPill state={boat.state === 'alert' ? 'alert' : 'clean'} label={boat.state === 'alert' ? 'Match' : 'No match'} />} />
              <KVStack label="Recommendation" value={canGrant ? 'Grant berth' : 'Decline & log'} />
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="btn btn-secondary" style={{ flex: 1, justifyContent: 'center' }} onClick={() => { setDecision('declined'); setStep(5); }}>
                <Icon name="x" />Decline & log
              </button>
              <button className="btn btn-primary" style={{ flex: 1, justifyContent: 'center', opacity: canGrant ? 1 : 0.4 }} disabled={!canGrant} onClick={() => { setDecision('granted'); setStep(5); }}>
                <Icon name="check" color="white" />Grant berth
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // ----- Done -----
  const ScreenDone = () => {
    if (!boat) return null;
    const granted = decision === 'granted';
    return (
      <div className="fade-up" style={{ maxWidth: 680, margin: '0 auto' }}>
        <div className="card">
          <div style={{ padding: 28, background: granted ? 'linear-gradient(180deg, var(--clean-soft), white)' : 'linear-gradient(180deg, var(--flag-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: granted ? 'var(--clean)' : 'var(--flag)', color: 'white', marginBottom: 14 }}>
              <Icon name={granted ? 'check' : 'x'} size={26} strokeWidth={2.4} color="white" />
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{granted ? 'Berth granted' : 'Berth declined — logged'}</div>
            <div style={{ fontSize: 13.5, color: 'var(--ink-2)', marginTop: 4 }}>
              {granted ? `Pontoon E · slot 14 · 17 May — 24 May 2026` : 'Approach recorded in audit trail with full check evidence.'}
            </div>
          </div>
          <div style={{ padding: 22, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            <KVStack label="Vessel" value={boat.name} />
            <KVStack label="Owner" value={boat.owner.name} />
            <KVStack label="Audit ref" value={'MAR-' + Math.floor(100000 + Math.random() * 899999)} mono />
            <KVStack label="Operator" value="D. Whitley · Berthing Office" />
          </div>
          {granted && (
            <div style={{ padding: 14, borderTop: '1px solid var(--line)', background: 'var(--paper-2)', fontSize: 12.5, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="bell" /> Insurance-lapse alerts active for the duration of the stay.
            </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" />New application</button>
            <button className="btn btn-primary"><Icon name="print" color="white" />Print berth pass</button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <PersonaShell
      persona={PERSONAS.find(p => p.id === 'marina')}
      steps={steps}
      currentStep={step}
      onStep={(i) => setStep(i)}
      onBack={onBack}
      hint="Demo doc auto-matches Salacia. Try other vessels to see flagged outcomes (Black Mamba = stolen)."
      injectStyle="@keyframes scanLine { 0%{top:40px} 50%{top:calc(100% - 80px)} 100%{top:40px} }"
    >
      {step === 0 && ScreenApplication()}
      {step === 1 && ScreenVerify()}
      {step === 2 && ScreenInsurance()}
      {step === 3 && ScreenFraud()}
      {step === 4 && ScreenDecision()}
      {step === 5 && ScreenDone()}
    </PersonaShell>
  );
};

Object.assign(window, { MarinaJourney });
