// Marine Broker / Dealer journey

const BrokerJourney = ({ onBack }) => {
  const [step, setStep] = useState(0);
  const [vesselId, setVesselId] = useState('');
  const [searching, setSearching] = useState(false);
  const [listed, setListed] = useState(false);
  const [offerName, setOfferName] = useState('');
  const [offerAmount, setOfferAmount] = useState('');
  const [certRef, setCertRef] = useState('');

  const steps = ['Pre-listing check', 'Review report', 'List with badge', 'Buyer offer check', 'Issue certificate'];
  const boat = BOATS.find(b => b.id === vesselId);

  const runCheck = () => {
    setSearching(true);
    setStep(1);
    setTimeout(() => setSearching(false), 1500);
  };
  const publishListing = () => {
    setListed(true);
    setStep(3);
  };
  const issueCert = () => {
    setCertRef('MCV-2026-' + Math.floor(10000 + Math.random() * 89999));
    setStep(5);
  };
  const reset = () => {
    setStep(0); setVesselId(''); setListed(false); setOfferName(''); setOfferAmount(''); setCertRef(''); setSearching(false);
  };

  const ScreenPreListing = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
      <div className="card">
        <CardHeader title="Pre-listing check" sub="Before taking a vessel onto the books" icon="doc" />
        <div style={{ padding: 18 }}>
          <label className="input-label">Vessel offered for sale</label>
          <BoatSelect value={vesselId} onChange={setVesselId} />
          <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label className="input-label">Seller name</label>
              <input className="input" placeholder="As shown on title" defaultValue={boat?.owner?.name || ''} />
            </div>
            <div>
              <label className="input-label">Listing price (target)</label>
              <input className="input mono" placeholder="£" defaultValue={boat ? '£' + Math.round(boat.value * 0.95).toLocaleString('en-GB') : ''} />
            </div>
          </div>
        </div>
        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>Confirms no outstanding finance, fraud, or ownership disputes.</span>
          <button className="btn btn-primary" disabled={!vesselId} onClick={runCheck} style={{ opacity: vesselId ? 1 : 0.5 }}>
            Run MarineCheck<Icon name="search" 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 }}>This month</div>
        <Stat label="Listings published" value="11" sub="2 with active offers" />
        <div style={{ height: 12 }} />
        <Stat label="Pre-listing checks" value="14" sub="2 caught flags before listing" />
        <div style={{ height: 12 }} />
        <Stat label="Verified-badge enquiries" value="+38%" sub="vs. non-verified listings" />
      </div>
    </div>
  );

  const ScreenReport = () => {
    if (searching) {
      return (
        <div className="fade-up card" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 52, height: 52, borderRadius: 12, background: 'var(--accent-soft)', color: 'var(--accent)', marginBottom: 16 }}>
            <LoadRing size={20} />
          </div>
          <div style={{ fontSize: 17, fontWeight: 600 }}>Compiling vessel history report…</div>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>Ownership chain · charges · claims · fraud markers</div>
        </div>
      );
    }
    if (!boat) return null;
    const clean = boat.flags.length === 0 && !boat.finance;
    return (
      <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="card" style={{ background: boat.state === 'alert' ? 'var(--alert-soft)' : boat.flags.length > 0 ? 'var(--flag-soft)' : 'var(--clean-soft)', borderColor: boat.state === 'alert' ? 'oklch(0.85 0.1 25)' : boat.flags.length > 0 ? 'oklch(0.85 0.1 60)' : 'oklch(0.85 0.07 165)' }}>
          <div style={{ padding: 20, display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', color: boat.state === 'alert' ? 'var(--alert)' : boat.flags.length > 0 ? 'var(--flag)' : 'var(--clean)' }}>
              <Icon name={boat.flags.length > 0 ? 'alert' : 'check'} size={22} strokeWidth={2} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.015em' }}>
                {boat.state === 'alert' ? 'Do not list — active alert' : boat.flags.length > 0 ? 'Flagged — advise seller before listing' : 'Clean title — eligible for Verified badge'}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>Full vessel history compiled — ownership, finance, claims, fraud.</div>
            </div>
            <span className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{boat.hin}</span>
          </div>
        </div>

        {boat.flags.map((f, i) => <FlagCard key={i} flag={f} />)}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <div className="card">
            <CardHeader title="Ownership chain" icon="user" />
            <div style={{ padding: 18 }}>
              {[
                { y: '2014 – 2019', n: 'P. Hartley (individual)' },
                { y: '2019 – 2021', n: 'Coastal Charter Ltd' },
                { y: `2021 – pres.`, n: boat.owner.name },
              ].map((o, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, padding: '8px 0', borderBottom: i < 2 ? '1px solid var(--line)' : 'none' }}>
                  <div style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--paper-2)', color: 'var(--ink-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, flexShrink: 0 }}>{i + 1}</div>
                  <div>
                    <div style={{ fontWeight: 500, fontSize: 13.5 }}>{o.n}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{o.y}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="card">
            <CardHeader title="Finance & claims" icon="pound" />
            <div style={{ padding: 18 }}>
              <KV label="Active charge" value={boat.finance ? `${boat.finance.lender} · ${formatGBP(boat.finance.balance)}` : 'None'} status={boat.finance ? 'flag' : 'clean'} />
              <KV label="Insurance" value={`${boat.insurance.insurer} (${boat.insurance.status})`} />
              <KV label="Claims history" value={`${boat.claims.length} on record`} />
              <KV label="Hull identity" value="Consistent across register" status="clean" />
            </div>
          </div>
        </div>

        <div className="card">
          <CardHeader title="Vessel summary" icon="boat" />
          <div style={{ padding: 18, display: 'flex', gap: 16 }}>
            <VesselThumb boat={boat} w={120} h={86} radius={8} />
            <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
              <KVStack label="Make/model" value={`${boat.make} ${boat.model}`} />
              <KVStack label="Year" value={boat.year} />
              <KVStack label="Length" value={boat.length} />
              <KVStack label="Type" value={boat.type} />
              <KVStack label="Last seen" value={boat.moorings} />
              <KVStack label="Declared value" value={formatGBP(boat.value)} mono />
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={() => setStep(0)}><Icon name="arrowLeft" />Back</button>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-secondary" onClick={reset}>Don't list</button>
            <button className="btn btn-primary" onClick={publishListing} disabled={boat.state === 'alert'} style={{ opacity: boat.state === 'alert' ? 0.4 : 1 }}>
              List with Verified badge<Icon name="arrowRight" color="white" />
            </button>
          </div>
        </div>
      </div>
    );
  };

  const ScreenList = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
      <div className="card" style={{ overflow: 'hidden' }}>
        <CardHeader title="Listing — published" sub="solentyachtbrokers.co.uk · live now" icon="link" right={<StatusPill state="clean" label="Live" />} />
        {/* Mock listing preview */}
        <div style={{ background: 'var(--paper-2)', padding: 18 }}>
          <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
            <div style={{ height: 200, position: 'relative' }}>
              <image-slot id={`listing-${boat?.id}`} shape="rounded" radius="10px 10px 0 0" placeholder={`${boat?.make} ${boat?.model} hero photo`} style={{ width: '100%', height: '100%', display: 'block' }}></image-slot>
              <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', gap: 6 }}>
                <span className="pill" style={{ background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(8px)', fontSize: 11.5, fontWeight: 600 }}>
                  <Icon name="check" size={11} color="var(--clean)" strokeWidth={2.4} /> MarineCheck Verified
                </span>
                <span className="pill" style={{ background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(8px)', fontSize: 11.5 }}>New listing</span>
              </div>
            </div>
            <div style={{ padding: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 18 }}>{boat.year} {boat.make} {boat.model}</div>
                  <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{boat.name} · {boat.length} · {boat.moorings}</div>
                </div>
                <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.015em' }}>{formatGBP(Math.round(boat.value * 0.95))}</div>
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
                <span className="pill" style={{ fontSize: 11 }}>{boat.type}</span>
                <span className="pill" style={{ fontSize: 11 }}>Clean title</span>
                <span className="pill" style={{ fontSize: 11 }}>{boat.claims.length} prior claim{boat.claims.length !== 1 ? 's' : ''}</span>
              </div>
            </div>
          </div>
        </div>
        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>Verified badge live until {formatDate(new Date(Date.now() + 90 * 86400000).toISOString())}.</span>
          <button className="btn btn-primary" onClick={() => setStep(3)}>Buyer offer received<Icon name="arrowRight" color="white" /></button>
        </div>
      </div>
      <div className="card card-pad" style={{ background: 'var(--paper-2)' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <div style={{ color: 'var(--clean)' }}><Icon name="sparkle" size={18} /></div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 13.5 }}>What the badge does</div>
            <ul style={{ paddingLeft: 16, margin: '8px 0 0', fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>
              <li>Embedded on your listings site + portals (YachtWorld, Apollo Duck)</li>
              <li>Differentiates from non-verified listings — buyer confidence</li>
              <li>Reduces broker liability — encumbrances caught early</li>
              <li>Refreshed automatically every 30 days</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );

  const ScreenOffer = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
      <div className="card">
        <CardHeader title="Buyer offer — second check" sub="Confirm clean title at point of offer" icon="user" />
        <div style={{ padding: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label className="input-label">Prospective buyer</label>
            <input className="input" placeholder="Full name" value={offerName} onChange={(e) => setOfferName(e.target.value)} />
          </div>
          <div>
            <label className="input-label">Offer amount</label>
            <input className="input mono" placeholder="£" value={offerAmount ? '£' + Number(offerAmount).toLocaleString('en-GB') : ''} onChange={(e) => setOfferAmount(e.target.value.replace(/[^0-9]/g, ''))} />
          </div>
        </div>
        <div style={{ padding: 18, paddingTop: 0 }}>
          <div style={{ padding: 14, borderRadius: 8, background: 'var(--clean-soft)', border: '1px solid oklch(0.85 0.07 165)', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <div style={{ color: 'var(--clean)', paddingTop: 1 }}><Icon name="check" size={16} strokeWidth={2.2} /></div>
            <div style={{ fontSize: 13, color: 'var(--ink)' }}>
              <strong>Re-check passed — no change since listing.</strong>
              <div style={{ color: 'var(--ink-2)', marginTop: 2, fontSize: 12.5 }}>Last checked 32 days ago. No new charges, claims, or fraud markers. Clean for sale.</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(2)}><Icon name="arrowLeft" />Back</button>
          <button className="btn btn-primary" onClick={issueCert} disabled={!offerName || !offerAmount} style={{ opacity: (offerName && offerAmount) ? 1 : 0.5 }}>
            Issue clean certificate<Icon name="doc" 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 }}>What the buyer receives</div>
        <ul style={{ margin: 0, paddingLeft: 16, fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.7 }}>
          <li>Certificate of clean title at offer date</li>
          <li>Full ownership chain (3 prior owners)</li>
          <li>Insurance & claims history</li>
          <li>HIN/serial verification</li>
          <li>Survey & maintenance summary (where available)</li>
        </ul>
      </div>
    </div>
  );

  const ScreenCertificate = () => (
    <div className="fade-up" style={{ maxWidth: 760, margin: '0 auto' }}>
      <div className="card" style={{ overflow: 'hidden' }}>
        <div style={{ padding: 28, textAlign: 'center', borderBottom: '1px solid var(--line)' }}>
          <MCLogo size="lg" />
          <div style={{ marginTop: 18, fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.12em' }} className="mono">Certificate of Clean Title</div>
          <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 8 }}>{boat?.name}</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)' }}>{boat?.make} {boat?.model} · {boat?.year}</div>
        </div>
        <div style={{ padding: 28, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 22 }}>
          <KVStack label="HIN" value={boat?.hin} mono />
          <KVStack label="Registration" value={boat?.reg} mono />
          <KVStack label="Length / type" value={`${boat?.length} · ${boat?.type}`} />
          <KVStack label="Last known moorings" value={boat?.moorings} />
          <KVStack label="Seller" value={boat?.owner.name} />
          <KVStack label="Buyer" value={offerName} />
          <KVStack label="Offer amount" value={offerAmount ? formatGBP(Number(offerAmount)) : '—'} mono />
          <KVStack label="Issued" value={new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })} />
          <KVStack label="Certificate ref" value={certRef} mono />
          <KVStack label="Validity" value="30 days from issue" />
        </div>
        <div style={{ padding: 28, borderTop: '1px solid var(--line)' }}>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 10, fontWeight: 500 }}>Findings at issue</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {[
              ['No outstanding charges', 'clean'],
              ['Hull identity consistent', 'clean'],
              ['No fraud markers', 'clean'],
              ['Insurance status verified', 'clean'],
              ['No stolen vessel alerts', 'clean'],
              ['Ownership chain clear', 'clean'],
            ].map(([t, s], i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                <Icon name="check" color="var(--clean)" strokeWidth={2.2} /> {t}
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: '20px 28px', borderTop: '1px solid var(--line)', background: 'var(--paper-2)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <SignatureMark width={120} height={32} />
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>P. Cavendish · Solent Yacht Brokers</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>verify.marinecheckhq.co.uk/{certRef}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>Issued by MarineCheck Ltd</div>
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16 }}>
        <button className="btn btn-secondary" onClick={reset}><Icon name="arrowLeft" />New check</button>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary"><Icon name="print" />Print</button>
          <button className="btn btn-primary"><Icon name="download" color="white" />PDF for sale pack</button>
        </div>
      </div>
    </div>
  );

  return (
    <PersonaShell
      persona={PERSONAS.find(p => p.id === 'broker')}
      steps={steps}
      currentStep={step}
      onStep={(i) => setStep(i)}
      onBack={onBack}
      hint="Try Solent Voyager (clean) · Northumbria (existing finance to advise on) · Black Mamba (do not list)"
    >
      {step === 0 && ScreenPreListing()}
      {step === 1 && ScreenReport()}
      {step === 2 && ScreenList()}
      {step === 3 && ScreenOffer()}
      {step === 4 && ScreenOffer()}
      {step === 5 && ScreenCertificate()}
    </PersonaShell>
  );
};

Object.assign(window, { BrokerJourney });
