// Use-a-Pass, Upload-more, History, Support screens
const P = window.PIVOT;
const I = window.I;

// ─────────────────────────────────────────────────────────────────────────
// USE A PASS — barcode display + actions
// ─────────────────────────────────────────────────────────────────────────
function UsePassScreen({ pass, onSave, onShare, onMarkUsed, onBack, isShared }) {
  return (
    <div style={{
      minHeight: '100%', background: P.navy, color: '#fff',
      padding: '60px 18px 30px', boxSizing: 'border-box',
      display: 'flex', flexDirection: 'column',
      backgroundImage: `radial-gradient(ellipse at top, ${P.navyLight} 0%, ${P.navyDeep} 70%)`,
    }}>
      {/* Top bar */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 999, border: 0,
          background: 'rgba(255,255,255,0.1)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{I.close('#fff')}</button>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,0.7)',
                      letterSpacing: 1.4, textTransform: 'uppercase' }}>
          {isShared ? 'Pass shared' : 'Active pass'}
        </div>
        <div style={{ width: 38 }}/>
      </div>

      {/* Pass */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column',
                    alignItems: 'center', justifyContent: 'center', padding: '20px 0' }}>
        <div style={{
          fontSize: 13, fontWeight: 700, color: P.cyanBright,
          letterSpacing: 1.6, textTransform: 'uppercase', marginBottom: 12,
        }}>Show this barcode at the gate</div>
        <div style={{ animation: 'pivotPassIn 0.4s cubic-bezier(.22,.9,.32,1)' }}>
          <PassTicket pass={pass} size="lg"/>
        </div>
        <div style={{ marginTop: 18, fontSize: 13, color: 'rgba(255,255,255,0.65)',
                      textAlign: 'center', maxWidth: 280, lineHeight: 1.5 }}>
          Brightness boosted automatically. Saving keeps this pass for later;
          marking used or sharing removes it from your inventory.
        </div>
      </div>

      {/* Action bar — Save / Share / Mark Used */}
      <div style={{
        background: 'rgba(255,255,255,0.06)', borderRadius: 22,
        padding: 8, display: 'flex', gap: 6,
        backdropFilter: 'blur(8px)',
      }}>
        <ActionTile label="Save" sub="for later" icon={I.bookmark('#fff', 22)} onClick={onSave}/>
        <ActionTile label="Share" sub="send to…" icon={I.share('#fff', 22)} onClick={onShare}
                    primary/>
        <ActionTile label="Mark Used" sub="remove" icon={I.check('#fff', 22)} onClick={onMarkUsed}/>
      </div>
    </div>
  );
}

function ActionTile({ label, sub, icon, onClick, primary }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, border: 0, cursor: 'pointer',
      background: primary ? P.cyan : 'rgba(255,255,255,0.08)',
      color: '#fff', borderRadius: 16,
      padding: '14px 6px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
      fontFamily: 'inherit',
      boxShadow: primary ? '0 8px 22px rgba(11,165,199,0.4)' : 'none',
    }}>
      {icon}
      <div style={{ fontSize: 14, fontWeight: 800, marginTop: 4 }}>{label}</div>
      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.65)' }}>{sub}</div>
    </button>
  );
}

// ── Native share sheet mock ──────────────────────────────────────────────
function ShareSheet({ open, onClose, onSent, pass }) {
  if (!open) return null;
  const targets = [
    { name: 'Sam Patel', sub: 'Messages', color: '#22C55E', initials: 'SP' },
    { name: 'Mom',       sub: 'Messages', color: '#EC4899', initials: 'M' },
    { name: 'Jordan B.', sub: 'WhatsApp', color: '#22C55E', initials: 'JB' },
    { name: 'Avery',     sub: 'Messages', color: '#0EA5E9', initials: 'A' },
  ];
  const apps = [
    { name: 'Messages', color: '#22C55E', glyph: '💬' },
    { name: 'Mail',     color: '#0EA5E9', glyph: '✉️' },
    { name: 'WhatsApp', color: '#22C55E', glyph: '💚' },
    { name: 'Copy',     color: '#64748B', glyph: '⎘' },
    { name: 'AirDrop',  color: '#3B82F6', glyph: '⌁' },
  ];
  return (
    <Sheet open={open} onClose={onClose}>
      <div style={{ paddingBottom: 6 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: P.muted,
                      letterSpacing: 1.4, textTransform: 'uppercase' }}>
          Share parking pass
        </div>
        <div style={{ marginTop: 4, fontSize: 16, color: P.navy, fontWeight: 700,
                      fontFamily: '"SF Mono", ui-monospace, monospace', letterSpacing: 1.2 }}>
          {pass?.code}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 14, overflowX: 'auto', padding: '14px 0',
                    margin: '0 -18px', paddingLeft: 18, paddingRight: 18 }}>
        {targets.map(t => (
          <div key={t.name} onClick={() => onSent(t.name)}
               style={{ width: 64, flexShrink: 0, textAlign: 'center', cursor: 'pointer' }}>
            <div style={{ width: 56, height: 56, borderRadius: 999,
                          background: t.color, color: '#fff',
                          fontSize: 18, fontWeight: 800,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          margin: '0 auto' }}>{t.initials}</div>
            <div style={{ fontSize: 11, color: P.navy, marginTop: 6, fontWeight: 600,
                          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {t.name}
            </div>
            <div style={{ fontSize: 10, color: P.muted }}>{t.sub}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 10, padding: '6px 0' }}>
        {apps.map(a => (
          <div key={a.name} onClick={() => onSent(`via ${a.name}`)}
               style={{ flex: 1, textAlign: 'center', cursor: 'pointer' }}>
            <div style={{ width: 52, height: 52, borderRadius: 14,
                          background: P.paper, fontSize: 22,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          margin: '0 auto' }}>{a.glyph}</div>
            <div style={{ fontSize: 11, color: P.navy, marginTop: 6, fontWeight: 600 }}>{a.name}</div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 12 }}>
        <PivotButton fullWidth variant="ghost" onClick={onClose}>Cancel</PivotButton>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// UPLOAD MORE PASSES (returning user)
// ─────────────────────────────────────────────────────────────────────────
function UploadScreen({ onBack, onComplete, currentCount }) {
  const [stage, setStage] = React.useState('idle'); // idle | scanning | dupes | done
  const start = () => {
    setStage('scanning');
    setTimeout(() => setStage('dupes'), 1400);
  };
  return (
    <div style={{ minHeight: '100%', background: P.paper }}>
      <ScreenHeader title="Upload Passes" onBack={onBack}/>
      <div style={{ padding: 20 }}>
        <div style={{ fontSize: 14, color: P.muted, lineHeight: 1.5, marginBottom: 18 }}>
          Drop in a new PDF from Pivot. We compare every barcode against your inventory
          ({currentCount} active) and skip duplicates automatically.
        </div>

        {stage === 'idle' && (
          <div onClick={start} style={{
            padding: '40px 20px', textAlign: 'center',
            background: '#fff', borderRadius: 22,
            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: 16, fontWeight: 700 }}>
              Choose PDF
            </div>
            <div style={{ marginTop: 4, color: P.muted, fontSize: 12 }}>
              From Files or Photos
            </div>
          </div>
        )}

        {stage === 'scanning' && (
          <div style={{ padding: '36px 20px', background: '#fff', borderRadius: 22, 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 PivotPasses_May2026.pdf
            </div>
            <div style={{ marginTop: 4, color: P.muted, fontSize: 12 }}>
              Cross-checking with your inventory…
            </div>
            <div style={{ marginTop: 18, 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={{ background: '#fff', borderRadius: 22, padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
              <div style={{ width: 38, height: 38, borderRadius: 12, background: '#FEF3C7',
                            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <span style={{ fontSize: 18 }}>⚠️</span>
              </div>
              <div>
                <div style={{ fontSize: 16, fontWeight: 800, color: P.navy }}>
                  Found 3 duplicates
                </div>
                <div style={{ fontSize: 13, color: P.muted }}>
                  Already in your inventory — skip them?
                </div>
              </div>
            </div>
            <div style={{ background: P.paper, borderRadius: 14, padding: '10px 14px',
                          fontFamily: '"SF Mono", monospace', fontSize: 13, color: P.muted, lineHeight: 1.8 }}>
              <div>EDE5BBAFE2 <span style={{ color: '#92400E' }}>· already imported</span></div>
              <div>6FE39C7112 <span style={{ color: '#92400E' }}>· already imported</span></div>
              <div>12194EE9D0 <span style={{ color: '#92400E' }}>· already imported</span></div>
            </div>
            <div style={{ marginTop: 14, padding: '10px 14px', borderRadius: 12,
                          background: '#ECFDF5', color: '#065F46',
                          fontSize: 13, fontWeight: 600 }}>
              ✓ 22 new passes ready to import
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
              <PivotButton variant="ghost" fullWidth onClick={onBack}>Cancel</PivotButton>
              <PivotButton variant="primary" fullWidth onClick={() => setStage('done')}>
                Skip dupes, import 22
              </PivotButton>
            </div>
          </div>
        )}

        {stage === 'done' && (
          <div style={{ background: '#fff', borderRadius: 22, padding: '28px 22px' }}>
            <div style={{ width: 56, height: 56, borderRadius: 16, background: '#DCFCE7',
                          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {I.check('#166534', 28)}
            </div>
            <div style={{ marginTop: 14, fontSize: 18, fontWeight: 800, color: P.navy }}>
              22 passes imported
            </div>
            <div style={{ marginTop: 4, fontSize: 13, color: P.muted }}>
              Your inventory now holds {currentCount + 22} passes.
            </div>
            <PivotButton fullWidth size="lg" variant="primary" onClick={onComplete}
                         style={{ marginTop: 20 }}>Done</PivotButton>
          </div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// HISTORY
// ─────────────────────────────────────────────────────────────────────────
function HistoryScreen({ passes, onBack }) {
  const [filter, setFilter] = React.useState('all'); // all | used | shared
  const items = passes
    .filter(p => p.status !== 'available')
    .filter(p => filter === 'all' || p.status === filter)
    .sort((a, b) => new Date(b.usedAt) - new Date(a.usedAt));
  return (
    <div style={{ minHeight: '100%', background: P.paper }}>
      <ScreenHeader title="History" onBack={onBack}/>
      {/* Filter */}
      <div style={{ padding: '4px 16px 16px', display: 'flex', gap: 8 }}>
        {['all', 'used', 'shared'].map(f => (
          <button key={f} onClick={() => setFilter(f)} style={{
            padding: '8px 14px', borderRadius: 999, border: 0, cursor: 'pointer',
            background: filter === f ? P.navy : '#fff',
            color: filter === f ? '#fff' : P.navy,
            fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
            textTransform: 'capitalize',
            boxShadow: filter === f ? 'none' : `inset 0 0 0 1px ${P.line}`,
          }}>{f}</button>
        ))}
      </div>
      <div style={{ padding: '0 16px 30px' }}>
        {items.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: P.muted, fontSize: 14 }}>
            No history yet.
          </div>
        ) : (
          <div style={{ background: '#fff', borderRadius: 16, overflow: 'hidden' }}>
            {items.map((p, i) => (
              <HistoryRow key={p.id} pass={p} isLast={i === items.length - 1}/>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function HistoryRow({ pass, isLast }) {
  const isShared = pass.status === 'shared';
  return (
    <div style={{
      padding: '14px 16px',
      borderBottom: isLast ? 'none' : `1px solid ${P.line}`,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 38, height: 38, borderRadius: 10,
          background: isShared ? '#DBEAFE' : '#FEE2E2',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {isShared ? I.share('#1E3A8A', 18) : I.check('#991B1B', 20)}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 14, fontWeight: 800, color: P.navy }}>
              {isShared ? `Shared with ${pass.sharedWith}` : 'Marked used'}
            </span>
            <StatusPill status={pass.status}/>
          </div>
          <div style={{ fontSize: 12, color: P.muted, marginTop: 2 }}>
            <span style={{ fontFamily: '"SF Mono", monospace', letterSpacing: 0.6 }}>{pass.code}</span>
            {' · '}{pass.location}
          </div>
        </div>
        <div style={{ fontSize: 12, color: P.muted, fontWeight: 600, textAlign: 'right' }}>
          {window.formatTime(pass.usedAt)}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// SUPPORT (mailto:)
// ─────────────────────────────────────────────────────────────────────────
function SupportScreen({ onBack }) {
  const mailto = 'mailto:support@pivotparking.com?subject=Pivot%20Pass%20App%20Support&body=Hi%20Pivot%20Parking%20support%20team%2C%0A%0A';
  return (
    <div style={{ minHeight: '100%', background: P.paper }}>
      <ScreenHeader title="Contact Support" onBack={onBack}/>
      <div style={{ padding: 20 }}>
        <div style={{ background: '#fff', borderRadius: 22, padding: 22 }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: P.cyan,
                        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {I.support('#fff', 28)}
          </div>
          <div style={{ marginTop: 14, fontSize: 22, fontWeight: 800, color: P.navy, letterSpacing: -0.4 }}>
            We're here to help.
          </div>
          <div style={{ marginTop: 8, fontSize: 14, color: P.muted, lineHeight: 1.5 }}>
            Tap below to open your email app with a pre-filled message to the
            Pivot Parking support team. Replies typically come within 1 business day.
          </div>
          <div style={{ marginTop: 20, padding: 14, borderRadius: 14, background: P.paper,
                        display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ fontSize: 18 }}>✉️</div>
            <div>
              <div style={{ fontSize: 13, color: P.muted }}>Sending to</div>
              <div style={{ fontSize: 15, fontWeight: 700, color: P.navy }}>support@pivotparking.com</div>
            </div>
          </div>
          <a href={mailto} style={{ textDecoration: 'none', display: 'block', marginTop: 18 }}>
            <PivotButton fullWidth size="lg" variant="primary">Open email app</PivotButton>
          </a>
          <div style={{ marginTop: 14, textAlign: 'center', fontSize: 13, color: P.muted }}>
            Or call <span style={{ color: P.navy, fontWeight: 700 }}>(704) 555-PARK</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Header ───────────────────────────────────────────────────────────────
function ScreenHeader({ title, onBack }) {
  return (
    <div style={{
      paddingTop: 60, paddingBottom: 14, paddingLeft: 16, paddingRight: 16,
      background: P.paper,
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <button onClick={onBack} style={{
        width: 38, height: 38, borderRadius: 999, border: 0, cursor: 'pointer',
        background: '#fff', boxShadow: `inset 0 0 0 1px ${P.line}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{I.back(P.navy)}</button>
      <div style={{ fontSize: 22, fontWeight: 800, color: P.navy, letterSpacing: -0.4 }}>{title}</div>
    </div>
  );
}

Object.assign(window, {
  UsePassScreen, ShareSheet, UploadScreen, HistoryScreen, SupportScreen, ScreenHeader,
});
