// Screens for the Pivot Parking pass app
const P = window.PIVOT;

// ── Icons (inline SVG) ───────────────────────────────────────────────────
const I = {
  ticket: (c = '#fff', s = 22) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3 7.5A1.5 1.5 0 014.5 6h15A1.5 1.5 0 0121 7.5V10a2 2 0 000 4v2.5A1.5 1.5 0 0119.5 18h-15A1.5 1.5 0 013 16.5V14a2 2 0 000-4V7.5z"
        stroke={c} strokeWidth="1.8"/>
      <path d="M9 9v6" stroke={c} strokeWidth="1.8" strokeDasharray="2 2"/>
    </svg>
  ),
  upload: (c = '#fff', s = 22) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M12 16V4M7 9l5-5 5 5" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M4 16v3a2 2 0 002 2h12a2 2 0 002-2v-3" stroke={c} strokeWidth="2" strokeLinecap="round"/>
    </svg>
  ),
  history: (c = '#fff', s = 22) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3 12a9 9 0 109-9M3 4v5h5" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M12 7v5l3 2" stroke={c} strokeWidth="2" strokeLinecap="round"/>
    </svg>
  ),
  support: (c = '#fff', s = 22) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M4 8a8 8 0 0116 0v6a4 4 0 01-4 4h-2" stroke={c} strokeWidth="2" strokeLinecap="round"/>
      <rect x="3" y="11" width="4" height="6" rx="1.5" stroke={c} strokeWidth="2"/>
      <rect x="17" y="11" width="4" height="6" rx="1.5" stroke={c} strokeWidth="2"/>
    </svg>
  ),
  share: (c = '#fff', s = 20) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M12 3v13M7 8l5-5 5 5" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M5 13v6a2 2 0 002 2h10a2 2 0 002-2v-6" stroke={c} strokeWidth="2" strokeLinecap="round"/>
    </svg>
  ),
  check: (c = '#fff', s = 20) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M5 12l5 5 9-11" stroke={c} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  bookmark: (c = '#fff', s = 20) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M6 3h12v18l-6-4-6 4V3z" stroke={c} strokeWidth="2" strokeLinejoin="round"/>
    </svg>
  ),
  back: (c = '#fff', s = 22) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M15 5l-7 7 7 7" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  close: (c = '#fff', s = 18) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M5 5l14 14M19 5L5 19" stroke={c} strokeWidth="2.2" strokeLinecap="round"/>
    </svg>
  ),
  pdf: (c = '#fff', s = 22) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M14 3H6a2 2 0 00-2 2v14a2 2 0 002 2h12a2 2 0 002-2V9l-6-6z" stroke={c} strokeWidth="1.8"/>
      <path d="M14 3v6h6" stroke={c} strokeWidth="1.8"/>
      <text x="12" y="17" textAnchor="middle" fontSize="6.5" fontWeight="800" fill={c}>PDF</text>
    </svg>
  ),
};

// ─────────────────────────────────────────────────────────────────────────
// LOGIN / SIGN UP
// ─────────────────────────────────────────────────────────────────────────
function LoginScreen({ onSignIn }) {
  const [mode, setMode] = React.useState('signin'); // signin | signup
  const [email, setEmail] = React.useState('robert.eason@example.com');
  const [pw, setPw]       = React.useState('••••••••••');
  const [name, setName]   = React.useState('');

  return (
    <div style={{
      minHeight: '100%', display: 'flex', flexDirection: 'column',
      background: `linear-gradient(180deg, ${P.navy} 0%, ${P.navyDeep} 55%, ${P.navyDeep} 100%)`,
      color: '#fff', padding: '70px 28px 30px', boxSizing: 'border-box', position: 'relative',
    }}>
      {/* Decorative arc */}
      <svg style={{ position: 'absolute', top: 80, right: -40, opacity: 0.18 }}
           width="240" height="160" viewBox="0 0 240 160" fill="none">
        <path d="M 20 130 Q 130 -10 230 80" stroke={P.cyan} strokeWidth="3" fill="none"/>
        <path d="M 220 70 L 232 80 L 220 92" stroke={P.cyan} strokeWidth="3" fill="none" strokeLinecap="round"/>
      </svg>

      <div style={{ marginTop: 30 }}>
        <PivotLogo size={36} light />
      </div>

      <div style={{ marginTop: 50 }}>
        <div style={{
          fontSize: 34, fontWeight: 800, letterSpacing: -0.6, lineHeight: 1.05,
        }}>
          {mode === 'signin' ? 'Welcome back.' : 'Create your account.'}
        </div>
        <div style={{
          marginTop: 10, fontSize: 16, color: 'rgba(255,255,255,0.7)', lineHeight: 1.45,
        }}>
          {mode === 'signin'
            ? 'Sign in to manage your parking passes.'
            : 'Get started by creating an account, then upload your pass sheet.'}
        </div>
      </div>

      <div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {mode === 'signup' && (
          <Field label="Full name" value={name} onChange={setName} placeholder="Robert Eason"/>
        )}
        <Field label="Email"    value={email} onChange={setEmail} type="email" placeholder="you@example.com"/>
        <Field label="Password" value={pw}    onChange={setPw}    type="password" placeholder="••••••••"/>
        {mode === 'signin' && (
          <div style={{
            color: P.cyanBright, fontSize: 14, fontWeight: 600,
            textAlign: 'right', marginTop: -4, cursor: 'pointer',
          }}>Forgot password?</div>
        )}
      </div>

      <div style={{ marginTop: 24 }}>
        <PivotButton fullWidth size="lg" variant="primary" onClick={() => onSignIn(mode === 'signup')}>
          {mode === 'signin' ? 'Sign in' : 'Create account'}
        </PivotButton>
      </div>

      <div style={{ marginTop: 'auto', textAlign: 'center', paddingTop: 30 }}>
        <span style={{ color: 'rgba(255,255,255,0.65)', fontSize: 14 }}>
          {mode === 'signin' ? "Don't have an account?" : 'Already have an account?'}
        </span>{' '}
        <span onClick={() => setMode(mode === 'signin' ? 'signup' : 'signin')}
              style={{ color: P.cyanBright, fontSize: 14, fontWeight: 700, cursor: 'pointer' }}>
          {mode === 'signin' ? 'Sign up' : 'Sign in'}
        </span>
      </div>
    </div>
  );
}

function Field({ label, value, onChange, type = 'text', placeholder }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.7)',
                    textTransform: 'uppercase', letterSpacing: 1.2, marginBottom: 6 }}>{label}</div>
      <input value={value} onChange={e => onChange(e.target.value)} type={type} placeholder={placeholder}
             style={{
               width: '100%', height: 52, padding: '0 16px', boxSizing: 'border-box',
               background: 'rgba(255,255,255,0.08)',
               border: '1.5px solid rgba(255,255,255,0.18)',
               borderRadius: 14, color: '#fff', fontSize: 16,
               fontFamily: 'inherit', outline: 'none',
             }}/>
    </label>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// FIRST-RUN UPLOAD (initial empty inventory)
// ─────────────────────────────────────────────────────────────────────────
function FirstUploadScreen({ onUpload, name }) {
  const [stage, setStage] = React.useState('intro'); // intro | scanning | done
  const start = () => {
    setStage('scanning');
    setTimeout(() => setStage('done'), 1800);
  };
  return (
    <div style={{
      minHeight: '100%', background: P.paper,
      padding: '60px 24px 40px', boxSizing: 'border-box',
      display: 'flex', flexDirection: 'column',
    }}>
      <PivotLogo size={26}/>
      <div style={{ marginTop: 32 }}>
        <div style={{ fontSize: 13, fontWeight: 800, color: P.cyan, letterSpacing: 1.2, textTransform: 'uppercase' }}>
          Step 1 of 1
        </div>
        <div style={{ fontSize: 30, fontWeight: 800, color: P.navy, letterSpacing: -0.6, marginTop: 6, lineHeight: 1.1 }}>
          {name ? `Welcome, ${name.split(' ')[0]}.` : 'Welcome.'}<br/>
          Upload your pass sheet.
        </div>
        <div style={{ fontSize: 15, color: P.muted, marginTop: 10, lineHeight: 1.45 }}>
          Pivot will email you a PDF with all your monthly passes. Drop it in here and we'll
          slice it into individual codes you can share or use.
        </div>
      </div>

      {stage === 'intro' && (
        <div onClick={start} style={{
          marginTop: 32, padding: '36px 20px', 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', 32)}
          </div>
          <div style={{ marginTop: 16, color: P.navy, fontSize: 17, fontWeight: 700 }}>
            Tap to choose PDF
          </div>
          <div style={{ marginTop: 4, color: P.muted, fontSize: 13 }}>
            or drag a file here · max 25 MB
          </div>
        </div>
      )}

      {stage === 'scanning' && (
        <div style={{ marginTop: 32, padding: '36px 20px',
                      background: '#fff', borderRadius: 22, textAlign: 'center' }}>
          <div style={{ width: 64, height: 64, margin: '0 auto', borderRadius: 18,
                        background: P.navy, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {I.pdf('#fff', 32)}
          </div>
          <div style={{ marginTop: 16, color: P.navy, fontSize: 17, fontWeight: 700 }}>
            Scanning RobertEason_1349025.pdf
          </div>
          <div style={{ marginTop: 4, color: P.muted, fontSize: 13 }}>
            Reading 5 pages · detecting barcodes…
          </div>
          <div style={{ marginTop: 18, height: 4, background: P.line, borderRadius: 4, overflow: 'hidden' }}>
            <div style={{
              height: '100%', background: P.cyan, width: '60%',
              animation: 'pivotProgress 1.6s ease forwards',
            }}/>
          </div>
        </div>
      )}

      {stage === 'done' && (
        <div style={{ marginTop: 32, padding: '28px 22px',
                      background: '#fff', borderRadius: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: '#DCFCE7',
                          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {I.check('#166534')}
            </div>
            <div>
              <div style={{ color: P.navy, fontSize: 17, fontWeight: 800 }}>40 passes imported</div>
              <div style={{ color: P.muted, fontSize: 13 }}>The Reed / Residential · expires 5/29/2026</div>
            </div>
          </div>
          <div style={{ marginTop: 18, padding: 14, borderRadius: 14, background: P.paper,
                        fontSize: 13, color: P.muted, lineHeight: 1.5 }}>
            We checked for duplicates against any earlier sheets — none found.
            Each pass gets its own barcode. We'll mark them used as you share.
          </div>
        </div>
      )}

      <div style={{ flex: 1 }}/>
      <PivotButton fullWidth size="lg" variant="primary"
                   disabled={stage !== 'done'}
                   onClick={onUpload}>
        Continue to your inventory
      </PivotButton>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// HOME — 4 buttons
// ─────────────────────────────────────────────────────────────────────────
function HomeScreen({ user, passes, onNav }) {
  const available = passes.filter(p => p.status === 'available').length;
  const used      = passes.filter(p => p.status !== 'available').length;
  return (
    <div style={{ minHeight: '100%', background: P.paper, paddingBottom: 30 }}>
      {/* Hero */}
      <div style={{
        background: `linear-gradient(160deg, ${P.navy} 0%, ${P.navyDeep} 100%)`,
        padding: '62px 22px 80px', position: 'relative', overflow: 'hidden',
        color: '#fff',
      }}>
        {/* Decorative arrows */}
        <svg style={{ position: 'absolute', top: 40, right: -30, opacity: 0.15 }}
             width="200" height="200" viewBox="0 0 200 200" fill="none">
          <path d="M 30 60 Q 100 0 180 70" stroke={P.cyan} strokeWidth="2.5" fill="none"/>
          <path d="M 180 140 Q 100 200 30 130" stroke={P.cyan} strokeWidth="2.5" fill="none"/>
        </svg>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <PivotLogo size={22} light/>
          <div onClick={() => onNav('history')} style={{
            width: 38, height: 38, borderRadius: 999,
            background: 'rgba(255,255,255,0.12)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}>
            <span style={{ fontSize: 13, fontWeight: 800, color: '#fff' }}>
              {user?.initials || 'RE'}
            </span>
          </div>
        </div>

        <div style={{ marginTop: 28, fontSize: 13, color: P.cyanBright, fontWeight: 700,
                      letterSpacing: 1.6, textTransform: 'uppercase' }}>
          Your inventory
        </div>
        <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', gap: 12 }}>
          <span style={{ fontSize: 64, fontWeight: 900, letterSpacing: -2.5, lineHeight: 1 }}>
            {available}
          </span>
          <span style={{ fontSize: 17, color: 'rgba(255,255,255,0.75)', fontWeight: 600 }}>
            passes available
          </span>
        </div>
        <div style={{ marginTop: 6, fontSize: 14, color: 'rgba(255,255,255,0.6)' }}>
          The Reed / Residential · {used} used this month
        </div>
      </div>

      {/* Cards (overlap hero) */}
      <div style={{ padding: '0 16px', marginTop: -54 }}>
        <ActionCard
          big primary
          title="Use a Pass"
          subtitle="Pull up a barcode to scan or share"
          icon={I.ticket('#fff', 28)}
          onClick={() => onNav('use')}
        />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 12 }}>
          <ActionCard
            title="Upload Passes"
            subtitle={`${available} on hand`}
            icon={I.upload(P.navy, 22)}
            onClick={() => onNav('upload')}
          />
          <ActionCard
            title="History"
            subtitle={`${used} entries`}
            icon={I.history(P.navy, 22)}
            onClick={() => onNav('history')}
          />
        </div>
        <ActionCard
          slim
          title="Contact Support"
          subtitle="support@pivotparking.com"
          icon={I.support(P.navy, 22)}
          onClick={() => onNav('support')}
        />
      </div>

      {/* Recent activity */}
      {passes.filter(p => p.status !== 'available').length > 0 && (
        <div style={{ padding: '24px 22px 0' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 13, fontWeight: 800, color: P.muted, letterSpacing: 1.4, textTransform: 'uppercase' }}>
              Recent activity
            </div>
            <div onClick={() => onNav('history')}
                 style={{ fontSize: 13, color: P.cyan, fontWeight: 700, cursor: 'pointer' }}>
              See all
            </div>
          </div>
          <div style={{ marginTop: 12, background: '#fff', borderRadius: 16, overflow: 'hidden' }}>
            {passes.filter(p => p.status !== 'available').slice(0, 3).map((p, i, arr) => (
              <ActivityRow key={p.id} pass={p} isLast={i === arr.length - 1}/>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function ActionCard({ title, subtitle, icon, onClick, big, primary, slim }) {
  if (primary) {
    return (
      <div onClick={onClick} style={{
        background: P.cyan, color: '#fff', borderRadius: 22,
        padding: '20px 22px', cursor: 'pointer',
        display: 'flex', alignItems: 'center', gap: 16,
        boxShadow: '0 12px 28px rgba(11,165,199,0.32)',
      }}>
        <div style={{ width: 56, height: 56, borderRadius: 16,
                      background: 'rgba(255,255,255,0.18)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {icon}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: -0.4 }}>{title}</div>
          <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.85)', marginTop: 2 }}>{subtitle}</div>
        </div>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
          <path d="M9 5l7 7-7 7" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
    );
  }
  if (slim) {
    return (
      <div onClick={onClick} style={{
        marginTop: 12, background: '#fff', borderRadius: 16,
        padding: '14px 16px', cursor: 'pointer',
        display: 'flex', alignItems: 'center', gap: 14,
        boxShadow: '0 1px 2px rgba(12,35,64,0.05), 0 4px 14px rgba(12,35,64,0.05)',
      }}>
        <div style={{ width: 40, height: 40, borderRadius: 12, background: P.paper,
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {icon}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: P.navy }}>{title}</div>
          <div style={{ fontSize: 12, color: P.muted }}>{subtitle}</div>
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
          <path d="M9 5l7 7-7 7" stroke={P.muted} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
    );
  }
  return (
    <div onClick={onClick} style={{
      background: '#fff', borderRadius: 18, padding: 16, cursor: 'pointer',
      boxShadow: '0 1px 2px rgba(12,35,64,0.05), 0 6px 18px rgba(12,35,64,0.06)',
      minHeight: 110, display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
    }}>
      <div style={{ width: 40, height: 40, borderRadius: 12, background: P.paper,
                    display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {icon}
      </div>
      <div>
        <div style={{ fontSize: 15, fontWeight: 800, color: P.navy, letterSpacing: -0.2 }}>{title}</div>
        <div style={{ fontSize: 12, color: P.muted, marginTop: 2 }}>{subtitle}</div>
      </div>
    </div>
  );
}

function ActivityRow({ pass, isLast }) {
  const map = {
    used:   { fg: '#991B1B', bg: '#FEE2E2', label: 'Used' },
    shared: { fg: '#1E3A8A', bg: '#DBEAFE', label: pass.sharedWith ? `Shared with ${pass.sharedWith}` : 'Shared' },
  }[pass.status] || {};
  return (
    <div style={{
      padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: isLast ? 'none' : `1px solid ${P.line}`,
    }}>
      <div style={{ width: 8, height: 8, borderRadius: 999, background: map.bg, border: `2px solid ${map.fg}` }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: P.navy,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {map.label}
        </div>
        <div style={{ fontSize: 12, color: P.muted,
                      fontFamily: '"SF Mono", ui-monospace, monospace', letterSpacing: 0.6 }}>
          {pass.code}
        </div>
      </div>
      <div style={{ fontSize: 12, color: P.muted, fontWeight: 600 }}>
        {window.formatTime(pass.usedAt)}
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen, FirstUploadScreen, HomeScreen, I });
