// Pivot Parking Pass App — main shell + state machine
const P = window.PIVOT;

function PivotApp({ initialView = 'login', layout = 'mobile', startUse = false }) {
  // ── State ──────────────────────────────────────────────────────────────
  const [view, setView]     = React.useState(initialView);
  const [passes, setPasses] = React.useState(window.SAMPLE_PASSES);
  const [user, setUser]     = React.useState({
    name: 'Robert Eason',
    email: 'robert.eason@example.com',
    initials: 'RE',
  });
  const [activePass, setActivePass]   = React.useState(null);
  const [shareOpen, setShareOpen]     = React.useState(false);
  const [toast, setToast]             = React.useState(null);
  const [isFresh, setIsFresh]         = React.useState(false); // fresh signup → first upload

  // ── Actions ────────────────────────────────────────────────────────────
  const signIn = (isSignup) => {
    setIsFresh(isSignup);
    setView(isSignup ? 'first-upload' : 'home');
  };

  const usePass = () => {
    const next = passes.find(p => p.status === 'available');
    if (!next) {
      setToast({ kind: 'warn', msg: 'No passes available — upload more.' });
      return;
    }
    setActivePass(next);
    setView('use');
  };

  // Auto-trigger Use-a-Pass when toolbar shortcut requests it
  React.useEffect(() => {
    if (startUse) {
      const next = passes.find(p => p.status === 'available');
      if (next) {
        setActivePass(next);
        setView('use');
      }
    }
    // eslint-disable-next-line
  }, [startUse]);

  const savePass = () => {
    setView('home');
    setActivePass(null);
    setToast({ kind: 'info', msg: 'Pass saved for later.' });
  };

  const markUsed = () => {
    setPasses(ps => ps.map(p => p.id === activePass.id
      ? { ...p, status: 'used', usedAt: new Date().toISOString() } : p));
    setView('home');
    setActivePass(null);
    setToast({ kind: 'success', msg: 'Pass marked used.' });
  };

  const sharePass = (recipient) => {
    setShareOpen(false);
    setPasses(ps => ps.map(p => p.id === activePass.id
      ? { ...p, status: 'shared', sharedWith: recipient, usedAt: new Date().toISOString() } : p));
    setView('home');
    setActivePass(null);
    setToast({ kind: 'success', msg: `Pass sent to ${recipient}` });
  };

  // ── Renderer ───────────────────────────────────────────────────────────
  const renderScreen = () => {
    switch (view) {
      case 'login':
        return <LoginScreen onSignIn={signIn}/>;
      case 'first-upload':
        return <FirstUploadScreen name={user.name} onUpload={() => setView('home')}/>;
      case 'home':
        return <HomeScreen user={user} passes={passes} onNav={(target) => {
          if (target === 'use') usePass();
          else setView(target);
        }}/>;
      case 'use':
        return activePass && (
          <UsePassScreen
            pass={activePass}
            onSave={savePass}
            onShare={() => setShareOpen(true)}
            onMarkUsed={markUsed}
            onBack={() => { setView('home'); setActivePass(null); }}
          />
        );
      case 'upload':
        return <UploadScreen
          onBack={() => setView('home')}
          onComplete={() => { setView('home'); setToast({ kind: 'success', msg: '22 passes added.' }); }}
          currentCount={passes.filter(p => p.status === 'available').length}
        />;
      case 'history':
        return <HistoryScreen passes={passes} onBack={() => setView('home')}/>;
      case 'support':
        return <SupportScreen onBack={() => setView('home')}/>;
      default:
        return null;
    }
  };

  // ── Mobile (default) ───────────────────────────────────────────────────
  if (layout === 'mobile') {
    return (
      <>
        {renderScreen()}
        <ShareSheet open={shareOpen} onClose={() => setShareOpen(false)}
                    onSent={sharePass} pass={activePass}/>
        {toast && <Toast message={toast.msg} kind={toast.kind} onDone={() => setToast(null)}/>}
      </>
    );
  }

  // ── Desktop layout ─────────────────────────────────────────────────────
  return <DesktopApp
    view={view} setView={setView}
    passes={passes}
    user={user}
    activePass={activePass}
    setActivePass={setActivePass}
    usePass={usePass}
    savePass={savePass}
    markUsed={markUsed}
    sharePass={sharePass}
    shareOpen={shareOpen} setShareOpen={setShareOpen}
    toast={toast} setToast={setToast}
  />;
}

// ─────────────────────────────────────────────────────────────────────────
// DESKTOP — sidebar + content
// ─────────────────────────────────────────────────────────────────────────
function DesktopApp({
  view, setView, passes, user, activePass, setActivePass,
  usePass, savePass, markUsed, sharePass, shareOpen, setShareOpen, toast, setToast,
}) {
  const available = passes.filter(p => p.status === 'available').length;
  const used = passes.filter(p => p.status !== 'available').length;

  // Login: full-bleed
  if (view === 'login') {
    return (
      <div style={{ width: '100%', height: '100%', display: 'flex',
                    background: P.navyDeep }}>
        <div style={{ flex: 1, position: 'relative', overflow: 'hidden',
                      background: `radial-gradient(ellipse at 30% 40%, ${P.navyLight}, ${P.navyDeep})` }}>
          <div style={{ padding: 50 }}>
            <PivotLogo size={36} light/>
          </div>
          <div style={{ padding: '0 60px', maxWidth: 580 }}>
            <div style={{ marginTop: 80, color: '#fff', fontSize: 56, fontWeight: 900,
                          letterSpacing: -1.5, lineHeight: 1.05 }}>
              Park fast.<br/>Park easy.<br/>
              <span style={{ color: P.cyanBright }}>Park smart.</span>
            </div>
            <div style={{ marginTop: 24, color: 'rgba(255,255,255,0.72)', fontSize: 18, lineHeight: 1.5, maxWidth: 480 }}>
              Manage every parking pass Pivot sends you. Upload a sheet, share single
              passes with friends or family, and let us track what's been used.
            </div>
            <div style={{ marginTop: 44, display: 'flex', gap: 40 }}>
              <Stat n="50K+" label="Cars parked per day"/>
              <Stat n="19M+" label="Transactions per year"/>
            </div>
          </div>
        </div>
        <div style={{ width: 460, background: '#fff', display: 'flex', alignItems: 'center' }}>
          <div style={{ padding: '0 50px', width: '100%' }}>
            <DesktopLogin onSignIn={(isSignup) => setView(isSignup ? 'first-upload' : 'home')}/>
          </div>
        </div>
      </div>
    );
  }

  // First-upload onboarding (centered)
  if (view === 'first-upload') {
    return (
      <div style={{ width: '100%', height: '100%', background: P.paper,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
        <div style={{ width: 540, background: '#fff', borderRadius: 28, padding: 40,
                      boxShadow: '0 30px 60px rgba(12,35,64,0.12)' }}>
          <PivotLogo size={28}/>
          <div style={{ fontSize: 13, fontWeight: 800, color: P.cyan,
                        letterSpacing: 1.4, textTransform: 'uppercase', marginTop: 28 }}>
            Step 1 of 1
          </div>
          <div style={{ fontSize: 32, fontWeight: 800, color: P.navy, letterSpacing: -0.6, marginTop: 4 }}>
            Welcome, {user.name.split(' ')[0]}.
          </div>
          <div style={{ fontSize: 15, color: P.muted, marginTop: 8, lineHeight: 1.5 }}>
            Drop in the PDF of monthly passes Pivot emailed you and we'll cut it
            into individual barcodes ready to share or use.
          </div>
          <DesktopUploadDrop onDone={() => setView('home')}/>
        </div>
      </div>
    );
  }

  // Main app (sidebar layout)
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', background: P.paper }}>
      {/* Sidebar */}
      <div style={{ width: 260, background: '#fff', borderRight: `1px solid ${P.line}`,
                    display: 'flex', flexDirection: 'column', padding: '28px 16px' }}>
        <div style={{ padding: '0 8px' }}>
          <PivotLogo size={24}/>
        </div>
        <div style={{ marginTop: 36, display: 'flex', flexDirection: 'column', gap: 4 }}>
          <NavItem active={view === 'home'} onClick={() => setView('home')}
                   icon={I.ticket(view === 'home' ? '#fff' : P.navy, 20)} label="Inventory"/>
          <NavItem active={view === 'upload'} onClick={() => setView('upload')}
                   icon={I.upload(view === 'upload' ? '#fff' : P.navy, 20)} label="Upload Passes"/>
          <NavItem active={view === 'history'} onClick={() => setView('history')}
                   icon={I.history(view === 'history' ? '#fff' : P.navy, 20)} label="History"/>
          <NavItem active={view === 'support'} onClick={() => setView('support')}
                   icon={I.support(view === 'support' ? '#fff' : P.navy, 20)} label="Contact Support"/>
        </div>
        <div style={{ marginTop: 'auto', padding: 12, borderRadius: 14, background: P.paper,
                      display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 36, height: 36, borderRadius: 999, background: P.navy, color: '#fff',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 13, fontWeight: 800 }}>{user.initials}</div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: P.navy,
                          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name}</div>
            <div style={{ fontSize: 11, color: P.muted,
                          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.email}</div>
          </div>
        </div>
      </div>

      {/* Content */}
      <div style={{ flex: 1, overflow: 'auto', position: 'relative' }}>
        {view === 'home' && <DesktopInventory passes={passes} onUse={(p) => { setActivePass(p); setView('use'); }}
                                              onUseAny={usePass} available={available} used={used}/>}
        {view === 'use' && activePass && <DesktopUseView pass={activePass}
                                              onSave={savePass} onShare={() => setShareOpen(true)} onMarkUsed={markUsed}
                                              onBack={() => { setView('home'); setActivePass(null); }}/>}
        {view === 'upload' && <DesktopUpload currentCount={available}
                                              onBack={() => setView('home')}
                                              onComplete={() => { setView('home'); setToast({ kind: 'success', msg: '22 passes added.' }); }}/>}
        {view === 'history' && <DesktopHistory passes={passes}/>}
        {view === 'support' && <DesktopSupport/>}
      </div>

      {/* Share sheet (modal in desktop) */}
      {shareOpen && <DesktopShareModal pass={activePass} onClose={() => setShareOpen(false)} onSent={sharePass}/>}
      {toast && <Toast message={toast.msg} kind={toast.kind} onDone={() => setToast(null)}/>}
    </div>
  );
}

function Stat({ n, label }) {
  return (
    <div>
      <div style={{ fontSize: 36, fontWeight: 900, color: P.amber, letterSpacing: -1 }}>{n}</div>
      <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', fontWeight: 600 }}>{label}</div>
    </div>
  );
}

function NavItem({ active, icon, label, onClick }) {
  return (
    <div onClick={onClick} style={{
      padding: '11px 14px', borderRadius: 12, cursor: 'pointer',
      display: 'flex', alignItems: 'center', gap: 12,
      background: active ? P.navy : 'transparent',
      color: active ? '#fff' : P.navy,
      fontSize: 14, fontWeight: 700,
      transition: 'background 0.15s',
    }}>
      {icon}
      {label}
    </div>
  );
}

function DesktopLogin({ onSignIn }) {
  const [mode, setMode] = React.useState('signin');
  return (
    <div>
      <div style={{ fontSize: 28, fontWeight: 800, color: P.navy, letterSpacing: -0.6 }}>
        {mode === 'signin' ? 'Welcome back' : 'Create your account'}
      </div>
      <div style={{ marginTop: 6, fontSize: 14, color: P.muted }}>
        {mode === 'signin' ? 'Sign in to manage your parking passes.' : 'Sign up, then upload your pass sheet.'}
      </div>
      <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {mode === 'signup' && <DField label="Full name" placeholder="Robert Eason"/>}
        <DField label="Email" placeholder="you@example.com" defaultValue="robert.eason@example.com"/>
        <DField label="Password" type="password" defaultValue="••••••••••"/>
        {mode === 'signin' && <div style={{ color: P.cyan, fontSize: 13, fontWeight: 700,
                                              textAlign: 'right', cursor: 'pointer' }}>Forgot password?</div>}
      </div>
      <div style={{ marginTop: 22 }}>
        <PivotButton fullWidth size="lg" variant="primary" onClick={() => onSignIn(mode === 'signup')}>
          {mode === 'signin' ? 'Sign in' : 'Create account'}
        </PivotButton>
      </div>
      <div style={{ marginTop: 24, textAlign: 'center', fontSize: 13, color: P.muted }}>
        {mode === 'signin' ? "Don't have an account?" : 'Already have one?'}{' '}
        <span onClick={() => setMode(mode === 'signin' ? 'signup' : 'signin')}
              style={{ color: P.cyan, fontWeight: 700, cursor: 'pointer' }}>
          {mode === 'signin' ? 'Sign up' : 'Sign in'}
        </span>
      </div>
    </div>
  );
}

function DField({ label, type = 'text', placeholder, defaultValue }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: P.muted,
                    textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6 }}>{label}</div>
      <input type={type} placeholder={placeholder} defaultValue={defaultValue}
             style={{
               width: '100%', height: 46, padding: '0 14px', boxSizing: 'border-box',
               background: P.paper, border: `1.5px solid ${P.line}`,
               borderRadius: 12, color: P.ink, fontSize: 15,
               fontFamily: 'inherit', outline: 'none',
             }}/>
    </label>
  );
}

function DesktopUploadDrop({ onDone }) {
  const [stage, setStage] = React.useState('idle');
  const start = () => {
    setStage('scanning');
    setTimeout(() => setStage('done'), 1500);
  };
  return (
    <>
      {stage === 'idle' && (
        <div onClick={start} style={{
          marginTop: 24, padding: '50px 30px', textAlign: 'center',
          background: P.paper, borderRadius: 18, border: `2px dashed ${P.cyan}`, cursor: 'pointer',
        }}>
          <div style={{ width: 60, height: 60, margin: '0 auto', borderRadius: 16,
                        background: P.cyan, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {I.upload('#fff', 28)}
          </div>
          <div style={{ marginTop: 14, color: P.navy, fontSize: 17, fontWeight: 700 }}>
            Drop PDF here, or click to browse
          </div>
          <div style={{ marginTop: 4, color: P.muted, fontSize: 13 }}>Max 25 MB</div>
        </div>
      )}
      {stage === 'scanning' && (
        <div style={{ marginTop: 24, padding: '40px 20px', background: P.paper, borderRadius: 18, textAlign: 'center' }}>
          <div style={{ width: 60, height: 60, margin: '0 auto', borderRadius: 16,
                        background: P.navy, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {I.pdf('#fff', 28)}
          </div>
          <div style={{ marginTop: 14, color: P.navy, fontSize: 16, fontWeight: 700 }}>Reading RobertEason_1349025.pdf</div>
          <div style={{ marginTop: 18, height: 4, background: '#fff', borderRadius: 4, overflow: 'hidden' }}>
            <div style={{ height: '100%', background: P.cyan, animation: 'pivotProgress 1.4s ease forwards' }}/>
          </div>
        </div>
      )}
      {stage === 'done' && (
        <div style={{ marginTop: 24, padding: 22, background: '#ECFDF5', borderRadius: 16,
                      display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#DCFCE7',
                        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {I.check('#166534', 24)}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ color: '#065F46', fontSize: 16, fontWeight: 800 }}>40 passes imported</div>
            <div style={{ color: '#047857', fontSize: 13 }}>The Reed / Residential · expires 5/29/2026</div>
          </div>
        </div>
      )}
      <PivotButton fullWidth size="lg" variant="primary"
                   disabled={stage !== 'done'} onClick={onDone}
                   style={{ marginTop: 22 }}>
        Continue to inventory
      </PivotButton>
    </>
  );
}

function DesktopInventory({ passes, onUse, onUseAny, available, used }) {
  const list = passes.filter(p => p.status === 'available');
  return (
    <div style={{ padding: 40 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 800, color: P.cyan,
                        letterSpacing: 1.4, textTransform: 'uppercase' }}>Your inventory</div>
          <div style={{ fontSize: 38, fontWeight: 900, color: P.navy, letterSpacing: -1, marginTop: 4 }}>
            {available} <span style={{ fontSize: 18, color: P.muted, fontWeight: 600 }}>passes available</span>
          </div>
          <div style={{ fontSize: 14, color: P.muted, marginTop: 4 }}>
            The Reed / Residential · {used} used this month
          </div>
        </div>
        <PivotButton size="lg" variant="primary" icon={I.ticket('#fff', 20)} onClick={onUseAny}>
          Use a Pass
        </PivotButton>
      </div>

      <div style={{ marginTop: 28, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 18 }}>
        {list.map(p => (
          <div key={p.id} onClick={() => onUse(p)} style={{ cursor: 'pointer' }}>
            <PassTicket pass={p} size="sm"/>
          </div>
        ))}
      </div>
    </div>
  );
}

function DesktopUseView({ pass, onSave, onShare, onMarkUsed, onBack }) {
  return (
    <div style={{
      minHeight: '100%',
      backgroundImage: `radial-gradient(ellipse at top, ${P.navyLight} 0%, ${P.navyDeep} 70%)`,
      color: '#fff', padding: 40, boxSizing: 'border-box',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onBack} style={{
          padding: '10px 16px', borderRadius: 999, border: 0, cursor: 'pointer',
          background: 'rgba(255,255,255,0.1)', color: '#fff',
          fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>{I.back('#fff', 18)} Back to inventory</button>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.7)',
                      letterSpacing: 1.4, textTransform: 'uppercase' }}>Active pass</div>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
        <div style={{ display: 'flex', gap: 40, alignItems: 'center' }}>
          <div style={{ animation: 'pivotPassIn 0.4s cubic-bezier(.22,.9,.32,1)' }}>
            <PassTicket pass={pass} size="lg"/>
          </div>
          <div style={{ maxWidth: 300 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: P.cyanBright,
                          letterSpacing: 1.6, textTransform: 'uppercase' }}>
              Show this barcode at the gate
            </div>
            <div style={{ marginTop: 14, fontSize: 28, fontWeight: 800, letterSpacing: -0.6, lineHeight: 1.15 }}>
              Save it, share it, or mark used.
            </div>
            <div style={{ marginTop: 14, fontSize: 14, color: 'rgba(255,255,255,0.7)', lineHeight: 1.5 }}>
              Sharing sends the code via your messaging app and removes it from your
              inventory automatically.
            </div>
            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <PivotButton fullWidth size="lg" variant="primary" icon={I.share('#fff', 20)} onClick={onShare}>Share pass</PivotButton>
              <PivotButton fullWidth variant="secondary" icon={I.check('#fff', 18)} onClick={onMarkUsed}>Mark used</PivotButton>
              <PivotButton fullWidth variant="ghost" icon={I.bookmark(P.navy, 18)} onClick={onSave}>Save for later</PivotButton>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function DesktopUpload({ currentCount, onBack, onComplete }) {
  const [stage, setStage] = React.useState('idle');
  const start = () => { setStage('scanning'); setTimeout(() => setStage('dupes'), 1300); };
  return (
    <div style={{ padding: 40, maxWidth: 720 }}>
      <div style={{ fontSize: 28, fontWeight: 800, color: P.navy, letterSpacing: -0.6 }}>Upload Passes</div>
      <div style={{ fontSize: 14, color: P.muted, marginTop: 4 }}>
        Drop a new PDF from Pivot. We'll cross-check your inventory of {currentCount} for duplicates.
      </div>
      {stage === 'idle' && (
        <div onClick={start} style={{
          marginTop: 24, padding: '60px 30px', textAlign: 'center',
          background: '#fff', borderRadius: 22, border: `2px dashed ${P.cyan}`, cursor: 'pointer',
        }}>
          <div style={{ width: 64, height: 64, margin: '0 auto', borderRadius: 18,
                        background: P.cyan, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {I.upload('#fff', 30)}
          </div>
          <div style={{ marginTop: 16, color: P.navy, fontSize: 18, fontWeight: 700 }}>
            Drop PDF here, or click to browse
          </div>
        </div>
      )}
      {stage === 'scanning' && (
        <div style={{ marginTop: 24, background: '#fff', borderRadius: 22, padding: 30, textAlign: 'center' }}>
          <div style={{ color: P.navy, fontSize: 16, fontWeight: 700 }}>Scanning PivotPasses_May2026.pdf…</div>
          <div style={{ marginTop: 14, height: 4, background: P.line, borderRadius: 4, overflow: 'hidden' }}>
            <div style={{ height: '100%', background: P.cyan, animation: 'pivotProgress 1.2s ease forwards' }}/>
          </div>
        </div>
      )}
      {stage === 'dupes' && (
        <div style={{ marginTop: 24, background: '#fff', borderRadius: 22, padding: 28 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: '#FEF3C7',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>⚠️</div>
            <div>
              <div style={{ fontSize: 18, fontWeight: 800, color: P.navy }}>3 duplicates found</div>
              <div style={{ fontSize: 13, color: P.muted }}>Already in your inventory</div>
            </div>
          </div>
          <div style={{ marginTop: 16, padding: 14, borderRadius: 12, background: P.paper,
                        fontFamily: '"SF Mono", monospace', fontSize: 13, color: P.muted, lineHeight: 1.8 }}>
            <div>EDE5BBAFE2 · already imported</div>
            <div>6FE39C7112 · already imported</div>
            <div>12194EE9D0 · already imported</div>
          </div>
          <div style={{ marginTop: 14, padding: '10px 14px', borderRadius: 12,
                        background: '#ECFDF5', color: '#065F46', fontSize: 14, fontWeight: 600 }}>
            ✓ 22 new passes ready to import
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
            <PivotButton variant="ghost" onClick={onBack}>Cancel</PivotButton>
            <PivotButton variant="primary" onClick={onComplete}>Skip dupes, import 22</PivotButton>
          </div>
        </div>
      )}
    </div>
  );
}

function DesktopHistory({ passes }) {
  const items = passes.filter(p => p.status !== 'available')
    .sort((a, b) => new Date(b.usedAt) - new Date(a.usedAt));
  return (
    <div style={{ padding: 40 }}>
      <div style={{ fontSize: 28, fontWeight: 800, color: P.navy, letterSpacing: -0.6 }}>History</div>
      <div style={{ fontSize: 14, color: P.muted, marginTop: 4 }}>
        Every pass you've used or shared. {items.length} entries.
      </div>
      <div style={{ marginTop: 24, background: '#fff', borderRadius: 18, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr 1fr 0.8fr',
                      padding: '14px 24px', background: P.paper,
                      fontSize: 11, fontWeight: 800, color: P.muted,
                      letterSpacing: 1, textTransform: 'uppercase' }}>
          <div>Code</div><div>Action</div><div>Location</div><div style={{ textAlign: 'right' }}>When</div>
        </div>
        {items.map((p, i) => (
          <div key={p.id} style={{
            display: 'grid', gridTemplateColumns: '1fr 1.4fr 1fr 0.8fr',
            padding: '14px 24px', alignItems: 'center',
            borderTop: i === 0 ? 'none' : `1px solid ${P.line}`,
          }}>
            <div style={{ fontFamily: '"SF Mono", monospace', fontSize: 13,
                          color: P.navy, fontWeight: 700, letterSpacing: 0.6 }}>{p.code}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <StatusPill status={p.status}/>
              <span style={{ fontSize: 13, color: P.muted }}>
                {p.status === 'shared' ? `to ${p.sharedWith}` : 'at gate'}
              </span>
            </div>
            <div style={{ fontSize: 13, color: P.muted }}>{p.location}</div>
            <div style={{ fontSize: 13, color: P.muted, textAlign: 'right' }}>
              {window.formatTimeFull(p.usedAt)}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function DesktopSupport() {
  const mailto = 'mailto:support@pivotparking.com?subject=Pivot%20Pass%20App%20Support';
  return (
    <div style={{ padding: 40, maxWidth: 640 }}>
      <div style={{ fontSize: 28, fontWeight: 800, color: P.navy, letterSpacing: -0.6 }}>Contact Support</div>
      <div style={{ fontSize: 14, color: P.muted, marginTop: 4 }}>We typically reply within 1 business day.</div>
      <div style={{ marginTop: 24, background: '#fff', borderRadius: 22, padding: 30 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: P.cyan,
                        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {I.support('#fff', 28)}
          </div>
          <div>
            <div style={{ fontSize: 20, fontWeight: 800, color: P.navy }}>Email Pivot support</div>
            <div style={{ fontSize: 13, color: P.muted }}>support@pivotparking.com · (704) 555-PARK</div>
          </div>
        </div>
        <a href={mailto} style={{ textDecoration: 'none', display: 'block', marginTop: 22 }}>
          <PivotButton size="lg" variant="primary">Open email app</PivotButton>
        </a>
      </div>
    </div>
  );
}

function DesktopShareModal({ pass, onClose, onSent }) {
  const targets = [
    { name: 'Sam Patel', sub: 'Messages', initials: 'SP', color: '#22C55E' },
    { name: 'Mom',       sub: 'Messages', initials: 'M',  color: '#EC4899' },
    { name: 'Jordan B.', sub: 'WhatsApp', initials: 'JB', color: '#22C55E' },
    { name: 'Avery',     sub: 'Messages', initials: 'A',  color: '#0EA5E9' },
  ];
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, background: 'rgba(8,18,36,0.55)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 90,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 22, padding: 28, width: 420,
        boxShadow: '0 30px 80px rgba(0,0,0,0.4)',
      }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: P.muted,
                      letterSpacing: 1.4, textTransform: 'uppercase' }}>Share parking pass</div>
        <div style={{ marginTop: 4, fontSize: 17, color: P.navy, fontWeight: 700,
                      fontFamily: '"SF Mono", monospace', letterSpacing: 1.2 }}>
          {pass?.code}
        </div>
        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {targets.map(t => (
            <div key={t.name} onClick={() => onSent(t.name)} style={{ textAlign: 'center', cursor: 'pointer' }}>
              <div style={{ width: 56, height: 56, borderRadius: 999, background: t.color, color: '#fff',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            margin: '0 auto', fontSize: 17, fontWeight: 800 }}>{t.initials}</div>
              <div style={{ fontSize: 12, color: P.navy, marginTop: 6, fontWeight: 600 }}>{t.name}</div>
              <div style={{ fontSize: 10, color: P.muted }}>{t.sub}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 18, padding: '10px 14px', borderRadius: 12, background: P.paper,
                      fontSize: 13, color: P.muted }}>
          ⌁ Or copy the code to your clipboard.
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <PivotButton variant="ghost" fullWidth onClick={onClose}>Cancel</PivotButton>
          <PivotButton variant="primary" fullWidth onClick={() => onSent('clipboard')}>Copy code</PivotButton>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PivotApp });
