// flowDRIVER kit — Inbound + Outbound, phone + kiosk SIDE-BY-SIDE.
// One unified asset showing both driver-side paths in parallel for each
// journey direction. The driver picks a device; we render both so the
// reviewer can see the equivalence at every step.

const { useState, useMemo, useEffect } = React;

// ─── tiny inline icon set ─────────────────────────────────────────
const Icon = (paths) => ({ size = 18, className = '' }) =>
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" className={className}>{paths}</svg>;

const IUser    = Icon(<><circle cx="12" cy="8" r="3.5" /><path d="M5 20c0-3.866 3.134-7 7-7s7 3.134 7 7" /></>);
const ITruck   = Icon(<><path d="M2 8h12V4H2v4zM14 8h4l3 4v4h-7V8z" /><circle cx="6" cy="18" r="1.6" /><circle cx="17" cy="18" r="1.6" /></>);
const IPackage = Icon(<><path d="M12 2L3 7v10l9 5 9-5V7l-9-5z" /><path d="M12 22V12M3 7l9 5 9-5" /></>);
const ITrailer = Icon(<><rect x="3" y="7" width="14" height="9" rx="1" /><circle cx="7" cy="18" r="1.6" /><circle cx="14" cy="18" r="1.6" /></>);
const ICheck   = Icon(<path d="M5 12.5l4 4 10-10" strokeWidth="2" />);
const IArrow   = Icon(<><path d="M5 12h14M13 6l6 6-6 6" strokeWidth="2" /></>);

const Phone = ({ children, dark = false }) =>
  <IOSDevice width={310} height={730} dark={dark}>{children}</IOSDevice>;

// ─── Reusable atoms (same as prior) ───────────────────────────────
const Safari = ({ url = 'web.FreightRoll.com' }) =>
  <div className="fd-safari"><span className="aA">aA</span><span className="url">{url}</span><span className="refresh">↻</span></div>;

const BrandBand = ({ co = 'PickupCo.' }) =>
  <div className="fd-brand-band">
    <div className="welcome">
      <span><div className="name">Welcome Henry Walker</div><span className="date">TUESDAY 23 JUNE</span></span>
      <span className="avatar">HW</span>
    </div>
    <div className="biz">{co}</div>
  </div>;

const FRPill = ({ verb = '' }) =>
  <div className="fd-fr-pill">
    <span className="lockup">
      <span className="yard">FREIGHT</span><span className="roll">ROLL</span>
      <span className="fast">FAST PASS{verb ? ' ' + verb : ''}</span>
    </span>
    <span className="menu"><span /><span /><span /></span>
  </div>;

const FastPassChrome = ({ co = 'PickupCo.', verb = '', children, photoBg = false, url = 'web.FreightRoll.com' }) =>
  <div className="fd-page">
    <Safari url={url} />
    <BrandBand co={co} />
    <FRPill verb={verb} />
    <div className={`fd-body ${photoBg ? 'bg-photo' : ''}`}>{children}</div>
  </div>;

// ─── Phone screens ────────────────────────────────────────────────
const ScreenLock = () =>
  <div className="fd-page" style={{ padding: 0 }}>
    <div className="fd-lock">
      <div className="fd-lock-time">9:41</div>
      <div className="fd-lock-date">Monday, May 5</div>
      <div className="fd-lock-foot"><div className="icon">🔦</div><div className="icon">📷</div></div>
    </div>
  </div>;

const CameraSubject = ({ stage, subject, trapezoid = false, brackets = false }) =>
  <div className={`fd-camera-stage ${stage}`}>
    <div className="fd-camera-subject">{subject}</div>
    {trapezoid && <div className="fd-trap" />}
    {brackets && <>
      <div className="fd-lbracket tl" /><div className="fd-lbracket tr" />
      <div className="fd-lbracket bl" /><div className="fd-lbracket br" />
    </>}
  </div>;

const CamChrome = () => <>
  <div className="fd-cam-tabs">
    {['CINEMATIC','VIDEO','PHOTO','PORTRAIT','PANO'].map(t => <div key={t} className={`t ${t === 'PHOTO' ? 'active' : ''}`}>{t}</div>)}
  </div>
  <div className="fd-cam-shutter-row"><div className="fd-cam-thumb" /><div className="fd-cam-shutter" /><div className="fd-cam-swap">↺</div></div>
</>;

const ScreenCameraTruck = () =>
  <div className="fd-page" style={{ padding: 0 }}>
    <div className="fd-camera">
      <CameraSubject stage="truck-cab" subject="PickupCo. signage on truck door" trapezoid />
      <CamChrome />
    </div>
  </div>;

const ScreenShipment = ({ co = 'PickupCo.' }) =>
  <FastPassChrome co={co}>
    <div className="fd-row"><span className="ico"><IUser size={16} /></span><div className="body"><div className="k">Contact</div><div className="v">jake@TruckCo.com</div></div><span className="chev">›</span></div>
    <div className="fd-row"><span className="ico"><ITruck size={16} /></span><div className="body"><div className="k">Truck Number</div><div className="v">75689</div></div><span className="chev">›</span></div>
    <div className="fd-row"><span className="ico"><IPackage size={16} /></span><div className="body"><div className="k">Shipment</div><div className="v">548AG109AZ</div></div><span className="chev">›</span></div>
    <div className="fd-input-row"><span className="ico" style={{ color: 'var(--fd-cta)' }}><ITrailer size={16} /></span><div style={{ flex: 1 }}><div className="k">Trailer Number <span className="req">Required</span></div><input defaultValue="TT" /></div></div>
    <button className="fd-cta">Read Safety Agreement</button>
  </FastPassChrome>;

const ScreenScanPrompt = ({ co, title }) =>
  <FastPassChrome co={co} photoBg>
    <h2 className="fd-body-h" style={{ marginTop: 40 }}>{title}</h2>
    <button className="fd-cta" style={{ marginTop: 24 }}>Scan Now</button>
  </FastPassChrome>;

const ScreenCameraDoc = ({ subject = 'BOL document', stage = 'bol-doc' }) =>
  <div className="fd-page" style={{ padding: 0 }}>
    <div className="fd-camera">
      <CameraSubject stage={stage} subject={subject} brackets />
      <CamChrome />
    </div>
  </div>;

const ScreenSMS = ({ from = 'DeliveryCo.', body, link = false }) =>
  <div className="fd-page" style={{ padding: 0 }}>
    <div className="fd-sms">
      <div className="fd-sms-head"><span className="back">‹</span><span className="contact"><span className="avatar">DC</span><span className="name">{from} ›</span></span><span className="video">▶</span></div>
      <div className="fd-sms-day">Today 9:41</div>
      <div className="fd-sms-body">
        <div className="fd-bubble-them">{body}{link && <><br /><span className="link">Click here for instructions</span></>}</div>
      </div>
      <div className="fd-sms-composer"><span className="ico">📷</span><span className="ico">A</span><input placeholder="iMessage" /><span className="ico">🎙</span></div>
    </div>
  </div>;

const QRPattern = ({ size = 160 }) => {
  const cells = 21;
  const data = useMemo(() => {
    const grid = [];
    for (let y = 0; y < cells; y++) {
      const row = [];
      for (let x = 0; x < cells; x++) {
        const inFinder = (x < 7 && y < 7) || (x > 13 && y < 7) || (x < 7 && y > 13);
        if (inFinder) {
          const lx = (x > 13 ? x - 14 : x), ly = (y > 13 ? y - 14 : y);
          const isBorder = lx === 0 || lx === 6 || ly === 0 || ly === 6;
          const isCore = lx >= 2 && lx <= 4 && ly >= 2 && ly <= 4;
          row.push(isBorder || isCore ? 1 : 0);
        } else {
          row.push(((x * 7 + y * 13 + x * y) % 5 < 2) ? 1 : 0);
        }
      }
      grid.push(row);
    }
    return grid;
  }, []);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${cells} ${cells}`}>
      <rect width={cells} height={cells} fill="#fff" />
      {data.map((row, y) => row.map((v, x) => v ? <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" fill="#000" /> : null))}
    </svg>
  );
};

const ScreenGateOpenQR = ({ co = 'PickupCo.' }) =>
  <FastPassChrome co={co} photoBg>
    <div className="fd-gate-qr-card">
      <div className="verified-rail">MACHINE VERIFIED ✓</div>
      <div>
        <div className="qr"><QRPattern size={150} /></div>
        <div className="label">Use QR Code To Open Gate</div>
      </div>
    </div>
  </FastPassChrome>;

// ─── Kiosk screens ────────────────────────────────────────────────
const KioskFrame = ({ children, idle = false }) =>
  <div className={`fd-kiosk ${idle ? 'is-idle' : ''}`}>
    <div className="fd-kiosk-screen">{children}</div>
  </div>;

const KioskCard = ({ tabPair, children }) =>
  <div className="fd-kiosk-card">
    <div className="welcome"><span><div className="name">Welcome Henry Walker</div><span className="date">TUESDAY 23 JUNE</span></span><span className="av">HW</span></div>
    <div className="biz">PickupCo.</div>
    <div className="pill">
      <span className="lockup"><span className="yard">FREIGHT</span><span className="roll">ROLL</span><span className="fast">FAST PASS VERIFY</span></span>
      <span className="menu"><span /><span /><span /></span>
    </div>
    {tabPair && <div className="fd-kiosk-tabpair">
      <div className="fd-kiosk-tab">{tabPair[0]}</div>
      <div className="fd-kiosk-tab primary">{tabPair[1]}</div>
    </div>}
    <div className="fd-kiosk-body center">{children}</div>
  </div>;

const KTouchToStart = () =>
  <KioskFrame>
    <KioskCard>
      <div className="fd-kiosk-touch"><span className="finger">👆</span>Touch to start</div>
    </KioskCard>
  </KioskFrame>;

const KEnterSeal = () =>
  <KioskFrame>
    <KioskCard tabPair={['Help', 'Continue']}>
      <h2 className="fd-kiosk-h-md">Please Enter Seal Number</h2>
      <input className="fd-kiosk-seal-input" defaultValue="0411909" />
    </KioskCard>
  </KioskFrame>;

const KInfoVerify = () =>
  <KioskFrame>
    <KioskCard tabPair={['Update Info', 'My Info Is Correct']}>
      <div style={{ width: '100%', textAlign: 'left' }}>
        <div className="fd-kiosk-row"><span className="ic"><IUser size={18} /></span><div><div className="k">Contact</div><div className="v">jake@TruckCo.com</div></div><span className="ch">›</span></div>
        <div className="fd-kiosk-row"><span className="ic"><ITruck size={18} /></span><div><div className="k">Truck Number</div><div className="v">75689</div></div><span className="ch">›</span></div>
        <div className="fd-kiosk-row"><span className="ic"><IPackage size={18} /></span><div><div className="k">Shipment Number</div><div className="v">12AB3C1489</div></div><span className="ch">›</span></div>
        <div className="fd-kiosk-row"><span className="ic"><ITrailer size={18} /></span><div><div className="k">Trailer Number</div><div className="v">TT5897841</div></div><span className="ch">›</span></div>
      </div>
    </KioskCard>
  </KioskFrame>;

const KBOLView = () =>
  <KioskFrame>
    <div style={{ flex: 1, padding: '14px 22px 18px', display: 'flex', flexDirection: 'column' }}>
      <div className="fd-kiosk-card" style={{ margin: 0 }}>
        <div className="biz" style={{ paddingTop: 12 }}>PickupCo.</div>
        <div className="pill"><span className="lockup"><span className="yard">FREIGHT</span><span className="roll">ROLL</span><span className="fast">FAST PASS VERIFY</span></span><span className="menu"><span /><span /><span /></span></div>
        <div className="fd-bol">
          <div className="fd-bol-head">
            <div className="fd-bol-title">Bill of Lading</div>
            <div className="fd-bol-barcode">{Array.from({ length: 22 }).map((_, i) => <span key={i} />)}</div>
          </div>
          <div className="fd-bol-meta">
            <div><span>Pickup:</span><span>A456ETPU</span></div>
            <div><span>Delivery:</span><span>107-42</span></div>
            <div><span>Seal:</span><span>123456789</span></div>
          </div>
          <div className="fd-bol-grid">
            <div><span className="lbl">Shipper:</span><span className="val">PickupCo.<br />1234 Shipping Lane</span></div>
            <div><span className="lbl">Consignee:</span><span className="val">Generic Consignee<br />5678 Receiving Rd</span></div>
            <div><span className="lbl">Carrier:</span><span className="val">Generic Carrier<br />910 Transport Blvd</span></div>
          </div>
          <div className="fd-bol-table">
            <div className="row head"><span>Description</span><span>Qty</span><span>Lbs</span><span>Dim (in)</span><span /></div>
            <div className="row"><span>Item 1</span><span>20</span><span>120</span><span>10×10×10</span><span>⋮</span></div>
            <div className="row"><span>Item 2</span><span>50</span><span>60</span><span>20×20×20</span><span>⋮</span></div>
          </div>
        </div>
        <button className="fd-cta" style={{ margin: '10px 18px 14px', width: 'calc(100% - 36px)' }}>Close</button>
      </div>
    </div>
  </KioskFrame>;

const Signature = () =>
  <svg viewBox="0 0 200 60" fill="none" stroke="#111" strokeWidth="2.2" strokeLinecap="round">
    <path d="M14 38 C 22 18, 32 18, 38 32 C 44 46, 50 30, 58 30 L 64 36 L 70 26 L 80 36 C 90 44, 100 22, 112 30 C 124 38, 130 22, 140 30 L 150 38 L 162 24 C 170 14, 180 24, 188 38" />
  </svg>;

const KSignShipment = () =>
  <KioskFrame>
    <KioskCard tabPair={['See Bill of Lading', 'Accept Shipment']}>
      <div style={{ width: '100%', textAlign: 'left' }}>
        <div className="fd-sig-prompt">Please sign for shipment:<br /><strong>548AG109AZ</strong></div>
        <div className="fd-sig-pad"><Signature /></div>
      </div>
    </KioskCard>
  </KioskFrame>;

const KThankYou = () =>
  <KioskFrame>
    <div className="fd-kiosk-card">
      <div className="biz" style={{ paddingTop: 12 }}>PickupCo.</div>
      <div className="pill"><span className="lockup"><span className="yard">FREIGHT</span><span className="roll">ROLL</span><span className="fast">FAST PASS VERIFY</span></span><span className="menu"><span /><span /><span /></span></div>
      <div className="fd-kiosk-thanks">
        <h3>Thank you!</h3>
        <p>Pick up your printed copies below.</p>
        <p>A message containing the bill of lading has been sent to your mobile device.</p>
      </div>
    </div>
    <div className="fd-kiosk-print"><span className="dot" />PRINTING · BOL × 3 · YARD PASS × 1</div>
    <div className="fd-kiosk-paper" />
  </KioskFrame>;

// Idle kiosk panel — shown when this step is phone-only
const KioskIdle = ({ label = 'Touch to start' }) =>
  <KioskFrame idle>
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: 'rgba(255,255,255,0.5)' }}>
      <div style={{ fontSize: 36, marginBottom: 14 }}>🛏</div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase' }}>Kiosk Idle</div>
      <div style={{ marginTop: 6, fontSize: 13, color: 'rgba(255,255,255,0.65)' }}>{label}</div>
    </div>
  </KioskFrame>;

const PhoneIdle = ({ label = 'Phone in pocket' }) =>
  <Phone>
    <div className="fd-page" style={{ padding: 0, background: '#0B0F14' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: 'rgba(255,255,255,0.5)' }}>
        <div style={{ fontSize: 36, marginBottom: 14 }}>📵</div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)' }}>Phone Idle</div>
        <div style={{ marginTop: 6, fontSize: 13, color: 'rgba(255,255,255,0.65)' }}>{label}</div>
      </div>
    </div>
  </Phone>;

// ─── Journey step matrix ──────────────────────────────────────────
// Each row = one moment in time. Phone + kiosk show what's on each
// device at that moment. Either may be `null` (renders idle state).

// Driver scans the posted site QR placard at the entrance. The QR
// is a stand-in — its URL deep-links to web.FreightRoll.com.
const ScreenSiteQRScan = () =>
  <div className="fd-page" style={{ padding: 0 }}>
    <div className="fd-camera">
      <div className="fd-camera-stage gate">
        <div style={{
          width: 180, padding: 14,
          background: '#fff', borderRadius: 8,
          boxShadow: '0 16px 40px rgba(0,0,0,0.55)',
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <QRPattern size={150} />
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 9,
            color: '#0B0F14', textAlign: 'center', letterSpacing: '0.10em',
          }}>
            SCAN TO CHECK IN<br/>
            <span style={{ color: '#00B4FF', fontWeight: 700 }}>web.FreightRoll.com</span>
          </div>
        </div>
        <div className="fd-trap" />
      </div>
      <CamChrome />
    </div>
  </div>;

// Driver landed at web.FreightRoll.com via the QR scan. First ask:
// type your 10-char load number from dispatch.
const ScreenEnterLoadID = ({ co = 'PickupCo.' }) =>
  <FastPassChrome co={co}>
    <h2 className="fd-body-h">Enter Load Number</h2>
    <p className="fd-body-sub">10 characters. Find this on your dispatch sheet or rate confirmation.</p>
    <div className="fd-input-row">
      <div style={{ flex: 1 }}>
        <div className="k">LOAD NUMBER</div>
        <input defaultValue="548AG109AZ" />
      </div>
    </div>
    <div className="fd-cta-pair">
      <button className="fd-cta secondary">Back</button>
      <button className="fd-cta">Continue</button>
    </div>
  </FastPassChrome>;

const PHOTO_BG = `url("${window.__resources && window.__resources.photoBg || '../../assets/og-proof-beats-promises.png'}")`;

const STEP_MATRIX = {
  outbound: [
    {
      moment: 'Scan site QR',
      ctx: 'Driver pulls up to the gate, opens phone camera, points at the posted FreightRoll QR placard. Lands at web.FreightRoll.com. No app install.',
      phone: () => <ScreenSiteQRScan />,
      kiosk: () => <KioskIdle label="Driver outside, in cab" />,
      active: 'phone',
      elapsed: '0s',
      paper: '6m',
      event: 'site_qr_scanned',
    },
    {
      moment: 'Enter load #',
      ctx: 'Driver types the 10-character load number from dispatch. This is the only manual entry needed before everything auto-populates.',
      phone: () => <ScreenEnterLoadID co="PickupCo." />,
      kiosk: () => <KioskIdle label="Driver on phone" />,
      active: 'phone',
      elapsed: '14s',
      paper: '9m',
      event: 'load_id_entered',
    },
    {
      moment: 'Identify shipment',
      ctx: 'Auto-populated from carrier + supplier integration. Driver confirms trailer #.',
      phone: () => <ScreenShipment co="PickupCo." />,
      kiosk: () => <KioskIdle label="Driver on phone" />,
      active: 'phone',
      elapsed: '18s',
      paper: '12m',
      event: 'shipment_identified',
    },
    {
      moment: 'Drop instructions',
      ctx: 'SMS pushes spot # + drop rules link. Native iMessage — outside the app.',
      phone: () => <ScreenSMS from="DeliveryCo." body="Please drop your empty trailer in spot 5." link />,
      kiosk: () => <KioskIdle label="Driver at trailer drop" />,
      active: 'phone',
      elapsed: '32s',
      paper: '16m',
      event: 'sms_drop_dispatched',
    },
    {
      moment: 'Pickup instructions',
      ctx: 'Second SMS: spot 10, seal #, "approach kiosk for BOL print."',
      phone: () => <ScreenSMS from="DeliveryCo." body={'Please pick up your loaded trailer in spot 10.\n\nApproach the kiosk inside the dock office to print your bill of lading.\n\nYour seal #: 123456'} />,
      kiosk: () => <KioskIdle label="Driver hasn't entered office" />,
      active: 'phone',
      elapsed: '46s',
      paper: '20m',
      event: 'sms_pickup_dispatched',
    },
    {
      moment: 'Office check-in',
      ctx: 'Driver enters dock office. Kiosk wakes from idle. Phone can stay in pocket here.',
      phone: () => <PhoneIdle label="Driver chose kiosk path" />,
      kiosk: () => <KTouchToStart />,
      active: 'kiosk',
      elapsed: '1m 10s',
      paper: '25m',
      event: 'kiosk_session_started',
    },
    {
      moment: 'Verify identity',
      ctx: 'Driver enters seal # received via SMS. Cross-references against shipment record.',
      phone: () => <ScreenScanPrompt co="PickupCo." title="Scan Bill of Lading" />,
      kiosk: () => <KEnterSeal />,
      active: 'kiosk',
      elapsed: '1m 28s',
      paper: '30m',
      event: 'seal_verified',
    },
    {
      moment: 'Confirm shipment',
      ctx: 'Phone & kiosk show the same data. Driver picks where to confirm.',
      phone: () => <ScreenCameraDoc subject="Bill of Lading" stage="bol-doc" />,
      kiosk: () => <KInfoVerify />,
      active: 'either',
      elapsed: '1m 50s',
      paper: '34m',
      event: 'shipment_confirmed',
    },
    {
      moment: 'View BOL',
      ctx: 'Kiosk renders the full Bill of Lading inline. Phone holds the scanned image.',
      phone: () => <ScreenScanPrompt co="PickupCo." title="Scan Seal Tag on Trailer" />,
      kiosk: () => <KBOLView />,
      active: 'kiosk',
      elapsed: '2m 14s',
      paper: '40m',
      event: 'bol_reviewed',
    },
    {
      moment: 'Sign for shipment',
      ctx: 'Kiosk signature pad. The one moment the kiosk is non-optional today (still working on touchless sig).',
      phone: () => <PhoneIdle label="Driver signing at kiosk" />,
      kiosk: () => <KSignShipment />,
      active: 'kiosk',
      elapsed: '2m 38s',
      paper: '46m',
      event: 'bol_signed',
    },
    {
      moment: 'Receipt + BOL print',
      ctx: 'Thermal printer outputs BOL × 3 + Yard Pass × 1. Same docs also pushed to phone via SMS.',
      phone: () => <ScreenSMS from="DeliveryCo." body={'Your signed BOL is available at the link below.\n\nDoc ID: BOL-548AG109AZ'} />,
      kiosk: () => <KThankYou />,
      active: 'both',
      elapsed: '2m 56s',
      paper: '52m',
      event: 'documents_issued',
    },
    {
      moment: 'Open gate',
      ctx: 'Driver returns to cab. Gate QR on phone → MACHINE VERIFIED. Gate opens.',
      phone: () => <ScreenGateOpenQR co="PickupCo." />,
      kiosk: () => <KioskIdle label="Session closed" />,
      active: 'phone',
      elapsed: '3m 28s',
      paper: '63m',
      event: 'gate_opened',
    },
  ],
  inbound: [
    {
      moment: 'Scan site QR',
      ctx: 'Same first step as outbound: driver scans the posted FreightRoll QR with their phone camera. Lands at web.FreightRoll.com.',
      phone: () => <ScreenSiteQRScan />,
      kiosk: () => <KioskIdle label="Driver outside, in cab" />,
      active: 'phone',
      elapsed: '0s',
      paper: '6m',
      event: 'site_qr_scanned',
    },
    {
      moment: 'Enter load #',
      ctx: 'Driver types the load number from dispatch. Web app auto-detects this is an inbound POD shipment.',
      phone: () => <ScreenEnterLoadID co="DeliveryCo." />,
      kiosk: () => <KioskIdle label="Driver on phone" />,
      active: 'phone',
      elapsed: '14s',
      paper: '9m',
      event: 'load_id_entered',
    },
    {
      moment: 'Identify shipment',
      ctx: 'DeliveryCo. branded. Driver confirms trailer # for the inbound load.',
      phone: () => <ScreenShipment co="DeliveryCo." />,
      kiosk: () => <KioskIdle label="Driver on phone" />,
      active: 'phone',
      elapsed: '18s',
      paper: '12m',
      event: 'shipment_identified',
    },
    {
      moment: 'Scan BOL',
      ctx: 'Pink L-brackets frame the document; OCR + brand-match captures it.',
      phone: () => <ScreenCameraDoc subject="Bill of Lading" stage="bol-doc" />,
      kiosk: () => <KioskIdle label="Driver at trailer" />,
      active: 'phone',
      elapsed: '38s',
      paper: '18m',
      event: 'bol_captured',
    },
    {
      moment: 'Office check-in',
      ctx: 'Driver enters dock office. Kiosk wakes. Phone can stay in pocket.',
      phone: () => <PhoneIdle label="Driver chose kiosk path" />,
      kiosk: () => <KTouchToStart />,
      active: 'kiosk',
      elapsed: '54s',
      paper: '22m',
      event: 'kiosk_session_started',
    },
    {
      moment: 'Verify identity',
      ctx: 'Seal # entry confirms the right shipment is being received.',
      phone: () => <ScreenScanPrompt co="DeliveryCo." title="Scan Seal Tag on Trailer" />,
      kiosk: () => <KEnterSeal />,
      active: 'kiosk',
      elapsed: '1m 12s',
      paper: '26m',
      event: 'seal_verified',
    },
    {
      moment: 'Confirm shipment',
      ctx: 'Phone & kiosk show the same data. Driver picks where to confirm.',
      phone: () => <ScreenShipment co="DeliveryCo." />,
      kiosk: () => <KInfoVerify />,
      active: 'either',
      elapsed: '1m 30s',
      paper: '30m',
      event: 'shipment_confirmed',
    },
    {
      moment: 'Sign for delivery',
      ctx: 'Kiosk signature pad. Phone holds a copy of the rendered BOL.',
      phone: () => <PhoneIdle label="Driver signing at kiosk" />,
      kiosk: () => <KSignShipment />,
      active: 'kiosk',
      elapsed: '1m 52s',
      paper: '36m',
      event: 'bol_signed',
    },
    {
      moment: 'Receipt + print',
      ctx: 'Thermal printer outputs BOL + Yard Pass. SMS copy also delivered.',
      phone: () => <ScreenSMS from="DeliveryCo." body={'Your signed BOL is available at the link below.\n\nDoc ID: BOL-548AG109AZ'} />,
      kiosk: () => <KThankYou />,
      active: 'both',
      elapsed: '2m 14s',
      paper: '42m',
      event: 'documents_issued',
    },
    {
      moment: 'Open gate',
      ctx: 'MACHINE VERIFIED QR on phone opens the exit gate.',
      phone: () => <ScreenGateOpenQR co="DeliveryCo." />,
      kiosk: () => <KioskIdle label="Session closed" />,
      active: 'phone',
      elapsed: '2m 38s',
      paper: '50m',
      event: 'gate_opened',
    },
    {
      moment: 'Dock assignment',
      ctx: 'After gate, native SMS pushes the dock #. No radio, no clipboard.',
      phone: () => <ScreenSMS from="DeliveryCo." body="Please back into dock 5" />,
      kiosk: () => <KioskIdle label="Session closed" />,
      active: 'phone',
      elapsed: '2m 56s',
      paper: '58m',
      event: 'dock_assigned',
    },
  ],
};

// ═══════════════════════════════════════════════════════════════════
// TODAY vs FREIGHTROLL — comparison view
// ═══════════════════════════════════════════════════════════════════
const TODAY_STEPS = [
  ['Pull up to guard shack',         'Wait behind queue of trucks. Average wait: 6 mins.',                     '6m'],
  ['Hand DL + paperwork to guard',   'Guard manually inspects, photocopies on a worn copier.',                 '3m'],
  ['Guard radios to dispatch',       'Two-way radio chatter to confirm what dock is open. Misheard often.',    '4m'],
  ['Walk to dispatch office',        'Sometimes required to fill out paper trip sheet by hand.',               '5m'],
  ['Get verbal dock assignment',     'Dispatcher scribbles dock # on yellow sticky. No timestamp, no receipt.','2m'],
  ['Carbon-copy BOL',                'Three-part NCR form. Driver signs all three with a leaky pen.',          '4m'],
  ['Drive to dock by memory',        'No nav. Lost? Ask a spotter. They\'re on lunch.',                        '6m'],
  ['Wait for spotter at dock',       'Spotter is moving another trailer. Sit in cab.',                         '8m'],
  ['Drop/pickup trailer',            'Same physical work — only this part doesn\'t change.',                   '12m'],
  ['Walk paperwork back to office',  'Hand carbon copies to clerk. Hope they make it into the right pile.',    '5m'],
  ['Wait for printed gate pass',     'Clerk prints, stamps, signs. Hand it back to driver.',                   '4m'],
  ['Drive to exit gate',             'Guard re-inspects gate pass. Manually opens gate.',                      '4m'],
];

const NEW_STEPS = [
  ['Pull up — auto recognition',     'Camera reads truck QR; FreightRoll knows who you are.',                  '0m'],
  ['Tap on phone OR kiosk',          'Driver\'s choice. Same data either way.',                                '0m'],
  ['Confirm shipment info',          'Auto-populated from carrier + supplier integration. One tap.',           '1m'],
  ['Sign safety agreement',          'Once. Stored. Never asked again unless terms change.',                   '1m'],
  ['SMS instructions arrive',        'Dock #, seal #, drop rules — pushed natively. No radio.',                '0m'],
  ['Scan BOL + seal',                'Phone camera or kiosk paper scanner. Either works.',                     '2m'],
  ['Drop/pickup trailer',            'Same physical work — but now with chain-of-custody timestamps.',         '12m'],
  ['Show gate QR or kiosk receipt',  'MACHINE VERIFIED. Gate opens automatically.',                            '1m'],
];

const TodaySum = TODAY_STEPS.reduce((s, [, , t]) => s + parseInt(t), 0);
const NewSum = NEW_STEPS.reduce((s, [, , t]) => s + parseInt(t), 0);

const ComparisonView = () =>
  <>
    <div className="fd-vs">
      <div className="fd-vs-col today">
        <div className="fd-vs-col-head">
          <span className="eyebrow">The way it works today</span>
          <h2>Paper, radios, and the guard shack</h2>
          <p>What 95% of North-American yards still do — every truck, every shift, every day.</p>
        </div>
        <div className="fd-vs-steps">
          {TODAY_STEPS.map(([top, meta, time], i) =>
            <div key={i} className="fd-vs-step">
              <span className="n">{i + 1}</span>
              <span className="body"><span className="top">{top}</span><span className="meta">{meta}</span></span>
              <span className="time">{time}</span>
            </div>)}
        </div>
        <div className="fd-vs-foot"><span className="label">Total time per truck</span><span className="total">{TodaySum} min</span></div>
      </div>

      <div className="fd-vs-arrow-wrap">
        <div className="fd-vs-arrow"><IArrow size={28} /></div>
        <span>FreightRoll</span>
      </div>

      <div className="fd-vs-col now">
        <div className="fd-vs-col-head">
          <span className="eyebrow">The FreightRoll way</span>
          <h2>Verified, timestamped, & paperless</h2>
          <p>Driver picks their path — mobile camera + SMS, or the in-office kiosk. Same chain-of-custody output, either way.</p>
        </div>
        <div className="fd-vs-steps">
          {NEW_STEPS.map(([top, meta, time], i) =>
            <div key={i} className="fd-vs-step">
              <span className="n">{i + 1}</span>
              <span className="body"><span className="top">{top}</span><span className="meta">{meta}</span></span>
              <span className="time">{time}</span>
            </div>)}
        </div>
        <div className="fd-vs-foot"><span className="label">Total time per truck</span><span className="total">{NewSum} min</span></div>
      </div>
    </div>

    <div className="fd-vs-savings">
      <div className="fd-vs-stat"><span className="num">{TodaySum - NewSum} min</span><span className="lbl">Saved per truck</span><span className="src">{TodaySum}m → {NewSum}m</span></div>
      <div className="fd-vs-stat"><span className="num">{Math.round((1 - NewSum / TodaySum) * 100)}%</span><span className="lbl">Reduction in driver time at facility</span><span className="src">vs. paper baseline</span></div>
      <div className="fd-vs-stat"><span className="num">0</span><span className="lbl">Paper carbon copies</span><span className="src">vs. 3 per BOL</span></div>
      <div className="fd-vs-stat"><span className="num">100%</span><span className="lbl">Events cryptographically timestamped</span><span className="src">vs. 0% today</span></div>
    </div>

    <div className="fd-vs-callout">
      <div>
        <h3>The kiosk exists because drivers fork into two paths.</h3>
        <p>Some drivers will use their phone camera. Some won't. We built for both. The kiosk handles chain-of-custody capture for drivers who skip the mobile flow — same data, same trust, paper output if needed.</p>
        <p style={{ marginTop: 8 }}>SMS handles the "must-not-miss" beats — dock assignment, seal #, drop rules. Drivers check SMS reflexively even with poor signal. The app handles richer-UI moments. The kiosk handles signature + printed paperwork.</p>
      </div>
      <div className="ratio">{Math.round(TodaySum / NewSum)}×<span>faster</span></div>
    </div>
  </>;

// ═══════════════════════════════════════════════════════════════════
// App shell — Inbound/Outbound toggle, side-by-side phone+kiosk
// ═══════════════════════════════════════════════════════════════════
const App = () => {
  const [direction, setDirection] = useState('outbound');
  const [idx, setIdx] = useState(0);
  const [view, setView] = useState('journey');   // 'journey' only for now; vs-today removed pending real data
  const [playing, setPlaying] = useState(false);
  const [pulse, setPulse] = useState(false);
  const [showVideo, setShowVideo] = useState(false);

  const steps = STEP_MATRIX[direction];
  const step = steps[idx];

  const next = () => setIdx(i => Math.min(steps.length - 1, i + 1));
  const prev = () => setIdx(i => Math.max(0, i - 1));

  useEffect(() => {
    if (!playing || view !== 'journey') return;
    if (idx >= steps.length - 1) { setPlaying(false); return; }
    const t = setTimeout(() => setIdx(i => i + 1), 2400);
    return () => clearTimeout(t);
  }, [playing, idx, view, steps.length]);

  useEffect(() => {
    setPulse(true);
    const t = setTimeout(() => setPulse(false), 2400);
    return () => clearTimeout(t);
  }, [direction, view]);

  useEffect(() => {
    const onKey = (e) => {
      if (view !== 'journey') return;
      if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); next(); }
      if (e.key === 'ArrowLeft') { e.preventDefault(); prev(); }
      if (e.key === 'p' || e.key === 'P') setPlaying(p => !p);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [view, steps.length]);

  const switchDirection = (d) => { setDirection(d); setIdx(0); setPlaying(false); };

  return (
    <div className="fd-app">
      <aside className="fd-rail">
        <div className="fd-rail-brand">
          <svg width="26" height="26" viewBox="0 0 32 32" fill="none" stroke="#00B4FF" strokeWidth="2.5" strokeLinecap="round">
            <path d="M4 24 C8 24, 10 21, 14 17" />
            <path d="M14 30 C14 24, 14 21, 14 17" />
            <path d="M14 17 C18 13, 22 13, 28 18" />
            <circle cx="4" cy="24" r="2.5" fill="#00B4FF" />
            <circle cx="14" cy="30" r="2.5" fill="#00B4FF" />
            <circle cx="28" cy="18" r="2.5" fill="#00B4FF" />
            <circle cx="14" cy="17" r="3" fill="#00B4FF" />
          </svg>
          <div className="lockup">
            <span style={{ color: '#fff' }}>flow</span><span style={{ color: '#00B4FF' }}>DRIVER</span>
            <span className="by">CHECK-IN · UI KIT</span>
          </div>
        </div>

        <div className="fd-rail-section">
          <div className="fd-rail-heading">View</div>
          <div className="fd-toggle">
            <button className="is-active" onClick={() => setView('journey')}>Journey</button>
          </div>
          <div style={{ marginTop: 10, padding: '10px 12px', background: 'rgba(229,162,43,0.08)', border: '1px solid rgba(229,162,43,0.30)', borderRadius: 10, fontSize: 11, color: 'rgba(255,255,255,0.78)', lineHeight: 1.5 }}>
            <strong style={{ color: '#E5A22B' }}>vs. Today removed.</strong> The old comparison used invented timings. Hand me your real before/after metrics (avg gate time, dwell, BOL turnaround, paper count) and I'll rebuild it on facts.
          </div>
        </div>

        {view === 'journey' && <>
          <div className="fd-rail-section">
            <div className="fd-rail-heading">Direction</div>
            <div className="fd-toggle">
              <button className={direction === 'outbound' ? 'is-active' : ''} onClick={() => switchDirection('outbound')}>Outbound (BOL)</button>
              <button className={direction === 'inbound' ? 'is-active' : ''} onClick={() => switchDirection('inbound')}>Inbound (POD)</button>
            </div>
          </div>

          <div className="fd-rail-section">
            <div className="fd-rail-heading">{steps.length} moments</div>
            <div className="fd-step-list">
              {steps.map((s, i) =>
                <div key={i} className={`fd-step ${i === idx ? 'is-active' : ''} ${i < idx ? 'is-done' : ''}`} onClick={() => setIdx(i)}>
                  <span className="num">{i < idx ? <ICheck size={11} /> : (i + 1).toString().padStart(2, '0')}</span>
                  <span className="fd-step-label">
                    <span className="top">{s.moment}</span>
                    <span className="meta">{s.active === 'either' ? 'phone OR kiosk' : s.active === 'both' ? 'phone + kiosk' : s.active}</span>
                  </span>
                </div>)}
            </div>
          </div>
        </>}

        <div className="fd-rail-note">
          <strong>One asset, two paths.</strong> Phone path = camera + SMS for drivers who use their device. Kiosk path = touchscreen + DL swipe + printer for drivers who skip it. <strong>Same chain-of-custody output, either way.</strong>
        </div>

        {direction === 'outbound' && (
          <div className="fd-rail-section" style={{ marginTop: 14 }}>
            <div className="fd-rail-heading">Real footage</div>
            <button className="fd-video-toggle" onClick={() => setShowVideo(true)}>
              ▶ Watch real driver journey
            </button>
            <p style={{ fontSize: 11, color: 'rgba(255,255,255,0.50)', margin: '8px 0 0', lineHeight: 1.5 }}>
              Production capture from a Primo Brands outbound load — same flow you're stepping through.
            </p>
          </div>
        )}
      </aside>

      <main className="fd-stage">
        <div className="fd-stage-head">
          <p className="fd-stage-eyebrow">{direction === 'outbound' ? 'Outbound — BOL (pickup)' : 'Inbound — POD (delivery)'} · Moment {idx + 1} of {steps.length}</p>
          <h1 className="fd-stage-title">{step.moment}</h1>
          <p className="fd-stage-sub">{step.ctx}</p>
        </div>
        {false /* vs-today removed pending real data */ ? null
          : <>
              <div className={`fd-duo ${pulse ? 'is-pulsing' : ''}`} onClick={next} title="Tap to advance · ←/→ keys also work">
                <div className={`fd-duo-col ${step.active === 'phone' || step.active === 'either' || step.active === 'both' ? 'is-active' : 'is-passive'}`}>
                  <div className="fd-duo-cap">
                    <span className="dot" />
                    <span className="lbl">Phone</span>
                    {step.active === 'phone' && <span className="badge">Active</span>}
                    {step.active === 'either' && <span className="badge alt">Either</span>}
                    {step.active === 'both' && <span className="badge alt">Both</span>}
                  </div>
                  {step.phone()}
                </div>
                <div className="fd-duo-or">
                  <span className="line" />
                  <span className="word">OR</span>
                  <span className="line" />
                </div>
                <div className={`fd-duo-col ${step.active === 'kiosk' || step.active === 'either' || step.active === 'both' ? 'is-active' : 'is-passive'}`}>
                  <div className="fd-duo-cap">
                    <span className="dot" />
                    <span className="lbl">Kiosk</span>
                    {step.active === 'kiosk' && <span className="badge">Active</span>}
                    {step.active === 'either' && <span className="badge alt">Either</span>}
                    {step.active === 'both' && <span className="badge alt">Both</span>}
                  </div>
                  {step.kiosk()}
                </div>
                <span className="fd-tap-hint">Tap to advance</span>
              </div>

              <div className="fd-nav">
                <button onClick={(e) => { e.stopPropagation(); prev(); }} disabled={idx === 0}>← Prev</button>
                <button onClick={(e) => { e.stopPropagation(); setPlaying(p => !p); }} className={`fd-play ${playing ? 'is-on' : ''}`}>
                  {playing ? '■ Pause' : '▶ Auto-play'}
                </button>
                <span className="counter">{idx + 1} / {steps.length}</span>
                <button onClick={(e) => { e.stopPropagation(); next(); }} disabled={idx === steps.length - 1}>Next →</button>
              </div>

              <div className="fd-progress">
                {steps.map((s, i) => (
                  <span key={i} className={`dot ${i === idx ? 'is-active' : ''} ${i < idx ? 'is-done' : ''}`} onClick={() => setIdx(i)} />
                ))}
              </div>

              <div className="fd-meta-strip">
                <div className="slot"><span className="k">Elapsed</span><span className="v">{step.elapsed}</span></div>
                <div className="slot"><span className="k">Paper-process equivalent</span><span className="v paper">{step.paper}</span></div>
                <div className="slot"><span className="k">Chain-of-custody event</span><span className="v mini">{step.event}</span></div>
              </div>
            </>
        }
      </main>
      {showVideo && (
        <div className="fd-video-modal" onClick={() => setShowVideo(false)}>
          <div className="fd-video-modal-card" onClick={(e) => e.stopPropagation()}>
            <div className="fd-video-head">
              <div>
                <div className="fd-video-title">Real outbound driver journey</div>
                <div className="fd-video-sub">Production capture · Primo Brands → Walmart load</div>
              </div>
              <button className="fd-video-close" onClick={() => setShowVideo(false)}>✕</button>
            </div>
            <video
              src={window.__resources && window.__resources.outboundVideo || "../../assets/future-state-reference/driver-journey/outbound-journey.mp4"}
              controls
              autoPlay
              playsInline
              className="fd-video-player"
            />
            <div className="fd-video-foot">
              <span>Compare with the synthesized UI mockup on the left rail to see how the live flow maps to each step.</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
