// Boat Buyer / Consumer journey — public-facing marinecheckhq.co.uk

const ConsumerJourney = ({ onBack }) => {
  const [step, setStep] = useState(0);
  const [hin, setHin] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [cardOpen, setCardOpen] = useState(false);
  const [paying, setPaying] = useState(false);
  const [vesselId, setVesselId] = useState('');
  const [generating, setGenerating] = useState(false);
  const [decisionTaken, setDecisionTaken] = useState(null);

  const steps = ['Land on site', 'Enter & pay £22', 'Receive report', 'Review & decide', 'Finance & survey'];
  const boat = BOATS.find(b => b.id === vesselId);

  const pay = () => {
    setPaying(true);
    setTimeout(() => {
      // Auto-match what they typed to a boat; or default to Northumbria (flagged) for demo punch
      const found = BOATS.find(b => b.hin.toLowerCase().includes(hin.toLowerCase())) || BOATS.find(b => b.id === 'NTH-2017');
      setVesselId(found.id);
      setPaying(false);
      setCardOpen(false);
      setStep(2);
      setGenerating(true);
      setTimeout(() => setGenerating(false), 1500);
    }, 1500);
  };
  const reset = () => { setStep(0); setHin(''); setName(''); setEmail(''); setCardOpen(false); setPaying(false); setVesselId(''); setGenerating(false); setDecisionTaken(null); };

  // ---------- Step 0: Landing ----------
  const ScreenLanding = () => (
    <div className="fade-up">
      {/* Public site mock — outer browser frame is already provided by demo shell */}
      <div className="card" style={{ overflow: 'hidden' }}>
        {/* Site nav */}
        <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <MCLogo size="md" />
          <div style={{ display: 'flex', gap: 22, fontSize: 13, color: 'var(--ink-2)' }}>
            <span>How it works</span>
            <span>What's in the report</span>
            <span>For brokers</span>
            <span style={{ color: 'var(--ink)' }}>Sign in</span>
          </div>
        </div>
        <div style={{ padding: '64px 24px 56px', background: 'linear-gradient(180deg, white 0%, var(--paper-2) 100%)' }}>
          <div style={{ maxWidth: 720, margin: '0 auto', textAlign: 'center' }}>
            <div className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 16 }}>The UK Marine Data Check</div>
            <h1 style={{ fontSize: 48, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1.05, margin: 0, textWrap: 'balance' }}>
              Don't buy a boat with hidden debt.
            </h1>
            <p style={{ fontSize: 16, color: 'var(--ink-2)', marginTop: 16, maxWidth: 540, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.55 }}>
              Outstanding finance, fraud markers, claims history and prior owners — in a single £22 report.
              Instant. Issued before you commit a penny.
            </p>
            <div style={{ marginTop: 28, padding: 14, background: 'white', borderRadius: 12, border: '1px solid var(--line)', boxShadow: 'var(--shadow)', maxWidth: 560, marginLeft: 'auto', marginRight: 'auto', display: 'flex', gap: 10, alignItems: 'center' }}>
              <Icon name="search" color="var(--ink-3)" />
              <input
                className="input mono"
                style={{ border: 'none', padding: 0, fontSize: 14, flex: 1 }}
                placeholder="Enter HIN, registration, or vessel name"
                value={hin}
                onChange={(e) => setHin(e.target.value)}
              />
              <button className="btn btn-primary" onClick={() => setStep(1)}>Run check · £22</button>
            </div>
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--ink-3)', display: 'flex', justifyContent: 'center', gap: 18, alignItems: 'center' }}>
              <span><Icon name="check" size={12} color="var(--clean)" /> Instant report</span>
              <span><Icon name="check" size={12} color="var(--clean)" /> No subscription</span>
              <span><Icon name="check" size={12} color="var(--clean)" /> Pay by card</span>
            </div>
          </div>

          {/* Trust strip */}
          <div style={{ maxWidth: 920, margin: '64px auto 0', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
            {[
              { i: 'pound', t: 'Hidden finance', d: '1 in 9 boats sold privately carries an undisclosed charge.' },
              { i: 'shield', t: 'Insurance & claims', d: 'See prior claims across all participating insurers.' },
              { i: 'alert', t: 'Stolen markers', d: 'Cross-checked against police and insurer feeds.' },
            ].map((c, i) => (
              <div key={i} style={{ padding: 18, background: 'white', borderRadius: 10, border: '1px solid var(--line)' }}>
                <div style={{ color: 'var(--accent)', marginBottom: 10 }}><Icon name={c.i} size={20} /></div>
                <div style={{ fontWeight: 600, fontSize: 14.5 }}>{c.t}</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 4, lineHeight: 1.5 }}>{c.d}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: '18px 24px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-3)' }}>
          <span>© MarineCheck Ltd 2026</span>
          <span>Trading data from 17 insurers · 11 lenders · 38 marinas</span>
        </div>
      </div>
    </div>
  );

  // ---------- Step 1: Enter & pay ----------
  const ScreenEnterPay = () => (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
      <div className="card">
        <CardHeader title="Run your vessel check" sub="Takes under 60 seconds" icon="search" />
        <div style={{ padding: 18 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="input-label">Hull Identification Number (HIN)</label>
              <input className="input mono" placeholder="e.g. GB-PRC58V019-A0142" value={hin} onChange={(e) => setHin(e.target.value)} />
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4 }}>Don't know it? Try Northumbria (GB-SSM52-2017-0089), Solent Voyager, or Kestrel.</div>
            </div>
            <div>
              <label className="input-label">Vessel name (optional)</label>
              <input className="input" placeholder="As advertised" />
            </div>
            <div>
              <label className="input-label">Registration (optional)</label>
              <input className="input mono" placeholder="SSR …" />
            </div>
            <div>
              <label className="input-label">Your name</label>
              <input className="input" placeholder="Full name" value={name} onChange={(e) => setName(e.target.value)} />
            </div>
            <div>
              <label className="input-label">Email (for the report)</label>
              <input className="input" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} />
            </div>
          </div>
        </div>
        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>£22.00</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Single report · all-inclusive</div>
          </div>
          <button className="btn btn-primary" onClick={() => setCardOpen(true)} disabled={!hin || !name || !email} style={{ opacity: (hin && name && email) ? 1 : 0.5 }}>
            Continue to payment<Icon name="arrowRight" 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 }}>What's in the report</div>
        <ul style={{ margin: 0, paddingLeft: 16, fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.7 }}>
          <li>Ownership chain (all prior owners)</li>
          <li>Outstanding finance & registered charges</li>
          <li>Insurance status (active/lapsed)</li>
          <li>Claims history across the market</li>
          <li>Fraud and stolen-vessel markers</li>
          <li>Survey & maintenance records (where available)</li>
        </ul>
      </div>

      {/* Card overlay */}
      {cardOpen && (
        <div style={{ position: 'fixed', inset: 0, background: 'oklch(0.2 0.05 250 / 0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200, padding: 24 }} onClick={() => !paying && setCardOpen(false)}>
          <div className="card" style={{ width: 420, maxWidth: '100%', boxShadow: 'var(--shadow-lg)' }} onClick={(e) => e.stopPropagation()}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontWeight: 600 }}>Pay £22.00</div>
              <span style={{ fontSize: 11, color: 'var(--ink-3)' }}><Icon name="lock" size={10} /> Secured by Stripe</span>
            </div>
            <div style={{ padding: 18, display: 'grid', gap: 12 }}>
              <div>
                <label className="input-label">Card number</label>
                <input className="input mono" defaultValue="4242 4242 4242 4242" />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <div>
                  <label className="input-label">Expiry</label>
                  <input className="input mono" defaultValue="04 / 28" />
                </div>
                <div>
                  <label className="input-label">CVC</label>
                  <input className="input mono" defaultValue="123" />
                </div>
              </div>
            </div>
            <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)' }}>
              <button className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }} onClick={pay} disabled={paying}>
                {paying ? <><LoadRing /> Charging…</> : <>Pay £22.00<Icon name="check" color="white" /></>}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );

  // ---------- Step 2: Report ----------
  const ScreenReport = () => {
    if (generating) {
      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 }}>Compiling your report…</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)', marginTop: 6 }}>Cross-checking 17 insurers, 11 lenders, fraud feeds, and survey records.</div>
        </div>
      );
    }
    if (!boat) return null;
    const flagged = boat.flags.length > 0;
    return (
      <div className="fade-up" style={{ maxWidth: 920, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Verdict banner */}
        <div className="card" style={{ background: boat.state === 'alert' ? 'var(--alert-soft)' : flagged ? 'var(--flag-soft)' : 'var(--clean-soft)', borderColor: boat.state === 'alert' ? 'oklch(0.85 0.1 25)' : flagged ? 'oklch(0.85 0.1 60)' : 'oklch(0.85 0.07 165)' }}>
          <div style={{ padding: 24, display: 'flex', alignItems: 'center', gap: 18 }}>
            <div style={{ width: 52, height: 52, borderRadius: 12, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', color: boat.state === 'alert' ? 'var(--alert)' : flagged ? 'var(--flag)' : 'var(--clean)' }}>
              <Icon name={flagged ? 'alert' : 'check'} size={26} strokeWidth={2.2} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.02em' }}>
                {boat.state === 'alert' ? 'Walk away — this vessel has an active alert' : flagged ? 'Caution — hidden finance detected' : 'Clean — proceed with confidence'}
              </div>
              <div style={{ fontSize: 13.5, color: 'var(--ink-2)', marginTop: 3 }}>
                Report generated {new Date().toLocaleString('en-GB')} · ref MC-{boat.id} · valid 30 days
              </div>
            </div>
          </div>
        </div>

        {/* Vessel header */}
        <div className="card">
          <div style={{ padding: 22, display: 'flex', gap: 18 }}>
            <VesselThumb boat={boat} w={160} h={110} radius={10} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em' }}>{boat.name}</div>
              <div style={{ color: 'var(--ink-2)', fontSize: 14 }}>{boat.year} {boat.make} {boat.model} · {boat.length} · {boat.type}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                <span className="mono pill" style={{ fontSize: 11 }}>{boat.hin}</span>
                <span className="mono pill" style={{ fontSize: 11 }}>{boat.reg}</span>
                <span className="pill" style={{ fontSize: 11 }}>{boat.moorings}</span>
              </div>
            </div>
          </div>
        </div>

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

        {/* Sections */}
        <div className="card">
          <CardHeader title="Ownership chain" icon="user" />
          <table className="data-table">
            <thead><tr><th>Years</th><th>Owner</th><th>Kind</th></tr></thead>
            <tbody>
              <tr><td>2014 – 2019</td><td>P. Hartley</td><td>Individual</td></tr>
              <tr><td>2019 – 2021</td><td>Coastal Charter Ltd</td><td>Company</td></tr>
              <tr><td>2021 – present</td><td>{boat.owner.name}</td><td>{boat.owner.kind}</td></tr>
            </tbody>
          </table>
        </div>

        <div className="card">
          <CardHeader title="Outstanding finance" icon="pound" right={<StatusPill state={boat.finance ? 'flag' : 'clean'} label={boat.finance ? 'Active charge' : 'None'} />} />
          {boat.finance ? (
            <table className="data-table">
              <thead><tr><th>Lender</th><th>Type</th><th>Balance</th><th>Term ends</th><th>Status</th></tr></thead>
              <tbody><tr>
                <td>{boat.finance.lender}</td>
                <td>Marine mortgage</td>
                <td className="mono">{formatGBP(boat.finance.balance)}</td>
                <td>{boat.finance.term}</td>
                <td><StatusPill state="info" label={boat.finance.status} /></td>
              </tr></tbody>
            </table>
          ) : (
            <div style={{ padding: 18, color: 'var(--ink-3)', fontSize: 13.5 }}>No active charges registered against this vessel.</div>
          )}
        </div>

        <div className="card">
          <CardHeader title="Insurance & claims" icon="shield" />
          <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            <KVStack label="Current insurer" value={boat.insurance.insurer} />
            <KVStack label="Policy status" value={<StatusPill state={boat.insurance.status === 'Active' ? 'clean' : 'flag'} label={boat.insurance.status} />} />
            <KVStack label="Claims on record" value={`${boat.claims.length}`} />
            <KVStack label="Hull identity" value="Consistent" />
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={reset}><Icon name="arrowLeft" />New check</button>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-secondary"><Icon name="download" />Save PDF</button>
            <button className="btn btn-primary" onClick={() => setStep(3)}>Decide what to do<Icon name="arrowRight" color="white" /></button>
          </div>
        </div>
      </div>
    );
  };

  // ---------- Step 3: Decide ----------
  const ScreenDecide = () => {
    if (!boat) return null;
    const flagged = boat.flags.length > 0;
    return (
      <div className="fade-up" style={{ maxWidth: 760, margin: '0 auto' }}>
        <div className="card card-pad" style={{ marginBottom: 16 }}>
          <SectionHead eyebrow="Your decision" title={flagged ? "What you've found is leverage" : "You're cleared to proceed"} sub={flagged ? 'A registered charge or alert against this vessel gives you options. Most buyers either walk away or negotiate the price down by the outstanding balance.' : 'Clean title, valid insurance, no fraud markers. You can move ahead with confidence.'} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <button className="card card-pad" style={{ textAlign: 'left', cursor: 'pointer', border: decisionTaken === 'walk' ? '2px solid var(--alert)' : '1px solid var(--line)' }} onClick={() => setDecisionTaken('walk')}>
            <Icon name="arrowLeft" color="var(--alert)" size={18} />
            <div style={{ fontWeight: 600, marginTop: 10 }}>Walk away</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 4 }}>Decline this vessel. Search again with a different HIN.</div>
          </button>
          <button className="card card-pad" style={{ textAlign: 'left', cursor: 'pointer', border: decisionTaken === 'proceed' ? '2px solid var(--clean)' : '1px solid var(--line)' }} onClick={() => setDecisionTaken('proceed')}>
            <Icon name="check" color="var(--clean)" size={18} />
            <div style={{ fontWeight: 600, marginTop: 10 }}>Proceed with the purchase</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 4 }}>Use the report as part of your sale documentation.</div>
          </button>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16 }}>
          <button className="btn btn-ghost" onClick={() => setStep(2)}><Icon name="arrowLeft" />Back to report</button>
          <button className="btn btn-primary" onClick={() => setStep(4)} disabled={!decisionTaken} style={{ opacity: decisionTaken ? 1 : 0.5 }}>Next — finance & survey<Icon name="arrowRight" color="white" /></button>
        </div>
      </div>
    );
  };

  // ---------- Step 4: Finance & survey ----------
  const ScreenFinanceSurvey = () => {
    if (!boat) return null;
    return (
      <div className="fade-up" style={{ maxWidth: 920, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <SectionHead eyebrow="In the same session" title="Finance, survey, and broker — all in one place" sub="Optional. Partners who already know your vessel and your report." />

        <div className="card">
          <CardHeader title="Finance quotes — partner lenders" sub="Pre-approved against this vessel's report" icon="pound" />
          <table className="data-table">
            <thead><tr><th>Lender</th><th>Product</th><th>Rate</th><th>Monthly (over 60m)</th><th></th></tr></thead>
            <tbody>
              {[
                ['Coastline Capital', 'Marine mortgage', '7.4%', Math.round(boat.value * 0.4 / 50)],
                ['Anchor Lending Group', 'Asset-backed lease', '7.9%', Math.round(boat.value * 0.4 / 49)],
                ['Marine Finance Co.', 'Hire purchase', '8.2%', Math.round(boat.value * 0.4 / 48)],
              ].map((row, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 500 }}>{row[0]}</td>
                  <td>{row[1]}</td>
                  <td className="mono">{row[2]} APR</td>
                  <td className="mono">{formatGBP(row[3])}</td>
                  <td style={{ textAlign: 'right' }}><button className="btn btn-secondary" style={{ padding: '5px 10px', fontSize: 12 }}>Apply</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card">
          <CardHeader title="Surveyor panel" sub="Marine surveyors covering the vessel's location" icon="user" />
          <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            {[
              { n: 'M. Tarrant', firm: 'Tarrant Marine Surveys', area: 'Solent · IBI accredited', price: '£860 – £1,200' },
              { n: 'A. Birchall', firm: 'Coastline Surveyors', area: 'South coast · 22yrs', price: '£790 – £1,100' },
              { n: 'R. Khanna', firm: 'Khanna & Co.', area: 'South & East · YDSA', price: '£940 – £1,400' },
            ].map((s, i) => (
              <div key={i} style={{ padding: 14, border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper-2)' }}>
                <div style={{ fontWeight: 600, fontSize: 13.5 }}>{s.n}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{s.firm}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>{s.area}</div>
                <div style={{ fontSize: 12, marginTop: 8 }} className="mono">{s.price}</div>
                <button className="btn btn-secondary" style={{ width: '100%', justifyContent: 'center', marginTop: 10, fontSize: 12, padding: '6px' }}>Request quote</button>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={() => setStep(3)}><Icon name="arrowLeft" />Back</button>
          <button className="btn btn-primary" onClick={reset}><Icon name="check" color="white" />Done — start another check</button>
        </div>
      </div>
    );
  };

  return (
    <PersonaShell
      persona={PERSONAS.find(p => p.id === 'consumer')}
      steps={steps}
      currentStep={step}
      onStep={(i) => setStep(i)}
      onBack={onBack}
      hint="Demo: type anything as HIN — we'll auto-match to Northumbria (flagged) to show the punchy outcome."
    >
      {step === 0 && ScreenLanding()}
      {step === 1 && ScreenEnterPay()}
      {step === 2 && ScreenReport()}
      {step === 3 && ScreenDecide()}
      {step === 4 && ScreenFinanceSurvey()}
    </PersonaShell>
  );
};

Object.assign(window, { ConsumerJourney });
