// screens_entry.jsx — Home (amount) + Scan (auto-advancing). -> window.

// ── Shared header ─────────────────────────────────────────────
function ScreenHeader({ title, onBack, right, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 10px 6px 6px', flexShrink: 0 }}>
      {onBack
        ? <IconButton onClick={onBack} title="Back"><IconBack s={24} /></IconButton>
        : <div style={{ width: 12 }} />}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--display-weight)',
          fontSize: 'calc(21px * var(--fs,1))', letterSpacing: -0.3, lineHeight: 1.1 }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: 'var(--on-surface-var)', marginTop: 1 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// ── Step indicator (Divvy · Tip · Settle) ─────────────────────
function Steps({ active }) {
  const steps = ['Divvy', 'Tip', 'Settle'];
  const i = steps.indexOf(active);
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, padding: '0 18px 4px', flexShrink: 0 }}>
      {steps.map((s, k) => (
        <React.Fragment key={s}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 18, height: 18, borderRadius: 99, fontSize: 11, fontWeight: 800,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: k <= i ? 'var(--primary)' : 'var(--surface-variant)',
              color: k <= i ? 'var(--on-primary)' : 'var(--on-surface-var)' }}>
              {k < i ? '✓' : k + 1}
            </span>
            <span style={{ fontSize: 12, fontWeight: 700, color: k === i ? 'var(--on-surface)' : 'var(--on-surface-var)' }}>{s}</span>
          </div>
          {k < steps.length - 1 && <div style={{ width: 14, height: 2, borderRadius: 9, background: 'var(--outline-faint)' }} />}
        </React.Fragment>
      ))}
    </div>
  );
}

// ── Home / amount entry ───────────────────────────────────────
function HomeScreen({ state, set, currency, nav, clearBill }) {
  const cents = state.subtotalCents || 0;
  // every keypad edit asserts a clean MANUAL bill — so a previously scanned
  // receipt can never bleed into a typed amount.
  const manualPatch = (s) => ({ entry: 'manual', items: [], includeTax: false, taxRate: 0, merchant: '',
    splitMode: s.splitMode === 'items' ? 'even' : s.splitMode });
  const press = (d) => set((s) => ({ ...manualPatch(s), subtotalCents: Math.min((s.subtotalCents || 0) * 10 + d, 99999999) }));
  const back = () => set((s) => ({ ...manualPatch(s), subtotalCents: Math.floor((s.subtotalCents || 0) / 10) }));
  const dbl = () => set((s) => ({ ...manualPatch(s), subtotalCents: Math.min((s.subtotalCents || 0) * 100, 99999999) }));

  const Key = ({ label, onClick }) => (
    <button className="ta-press" onClick={onClick} style={{ border: 'none', background: 'transparent', cursor: 'pointer',
      borderRadius: 16, fontFamily: 'var(--font-display)', fontWeight: 600, color: 'var(--on-surface)',
      fontSize: 'calc(26px * var(--fs,1))', height: 52, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{label}</button>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 18px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <img src="app/divvy-icon.png" alt="DivvyTab" width="30" height="30" style={{ width: 30, height: 30, borderRadius: 9, display: 'block', objectFit: 'cover' }} />
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--display-weight)', fontSize: 18, letterSpacing: -0.3 }}>DivvyTab</span>
        </div>
        <IconButton variant="tonal" size={38} onClick={() => nav('history')} title="History"><IconClock s={20} /></IconButton>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 6, padding: '4px 18px', minHeight: 0 }}>
        <Label>Bill amount</Label>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <MoneyBig cents={cents} currency={currency} size={60} color={cents ? 'var(--on-surface)' : 'var(--on-surface-var)'} />
          {cents > 0 && (
            <button className="ta-press" onClick={clearBill} title="Clear amount" style={{ width: 30, height: 30, borderRadius: 99, border: 'none', cursor: 'pointer',
              background: 'var(--surface-variant)', color: 'var(--on-surface-var)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IconClose s={17} />
            </button>
          )}
        </div>
        <div style={{ fontSize: 13, color: 'var(--on-surface-var)' }}>Enter the total before tip</div>
      </div>

      <div style={{ padding: '0 18px 8px' }}>
        <button className="ta-press" onClick={() => nav('scan')} style={{ width: '100%', height: 50, borderRadius: 99, border: 'none', cursor: 'pointer',
          background: 'var(--secondary-container)', color: 'var(--on-secondary-container)', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9 }}>
          <IconScan s={20} /> Scan a receipt instead
        </button>
      </div>

      <div style={{ background: 'var(--surface)', borderTopLeftRadius: 28, borderTopRightRadius: 28, padding: '12px 18px 14px', boxShadow: '0 -6px 24px rgba(0,0,0,0.05)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 3, marginBottom: 10 }}>
          {[1,2,3,4,5,6,7,8,9].map((n) => <Key key={n} label={n} onClick={() => press(n)} />)}
          <Key label="00" onClick={dbl} />
          <Key label={0} onClick={() => press(0)} />
          <button className="ta-press" onClick={back} style={{ border: 'none', background: 'transparent', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--on-surface-var)' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6H9L3 12l6 6h11a1 1 0 001-1V7a1 1 0 00-1-1z"/><path d="M16 10l-4 4M12 10l4 4"/></svg>
          </button>
        </div>
        <Button disabled={cents <= 0} onClick={() => nav('split')}>Divvy It</Button>
      </div>
    </div>
  );
}

// ── Scan (simulated OCR, auto-advances) ───────────────────────
function ScanScreen({ state, set, nav, currency }) {
  const [phase, setPhase] = React.useState('aim'); // aim -> scanning -> done

  React.useEffect(() => {
    if (phase !== 'scanning') return;
    const t = setTimeout(() => setPhase('done'), 1800);
    return () => clearTimeout(t);
  }, [phase]);

  // auto-advance: once parsed, load receipt and jump straight to assignment
  React.useEffect(() => {
    if (phase !== 'done') return;
    const r = SAMPLE_RECEIPT;
    const t = setTimeout(() => {
      set({ entry: 'receipt', items: r.items.map((i) => ({ ...i, assignees: [] })),
        taxRate: r.taxRate, includeTax: true, splitMode: 'items', merchant: r.merchant,
        subtotalCents: r.items.reduce((a, i) => a + i.price, 0) });
      nav('assign');
    }, 1050);
    return () => clearTimeout(t);
  }, [phase]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="Scan receipt" onBack={() => nav('home')} />
      <div style={{ flex: 1, margin: '0 18px 16px', borderRadius: 28, position: 'relative', overflow: 'hidden',
        background: 'linear-gradient(160deg,#1a1f26,#0c0f14)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ width: 168, background: '#f6f3ec', borderRadius: 6, padding: '16px 14px', transform: 'rotate(-3deg)',
          boxShadow: '0 20px 50px rgba(0,0,0,0.5)', color: '#2a2620', fontFamily: 'var(--font-body)' }}>
          <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 13, letterSpacing: 1 }}>ROSEWOOD</div>
          <div style={{ textAlign: 'center', fontSize: 9, opacity: 0.6, marginBottom: 10 }}>TAVERN · TABLE 12</div>
          {SAMPLE_RECEIPT.items.slice(0, 5).map((i) => (
            <div key={i.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, marginBottom: 5, opacity: 0.85 }}>
              <span style={{ overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', maxWidth: 96 }}>{i.name}</span>
              <span className="ta-num">{fmt(i.price, currency)}</span>
            </div>
          ))}
          <div style={{ borderTop: '1px dashed #bbb', marginTop: 6, paddingTop: 6, display: 'flex', justifyContent: 'space-between', fontSize: 10, fontWeight: 800 }}>
            <span>TOTAL</span><span className="ta-num">{fmt(SAMPLE_RECEIPT.items.reduce((a,i)=>a+i.price,0), currency)}</span>
          </div>
        </div>

        {['tl','tr','bl','br'].map((k) => (
          <div key={k} style={{ position: 'absolute',
            top: k[0]==='t'?18:'auto', bottom: k[0]==='b'?18:'auto', left: k[1]==='l'?18:'auto', right: k[1]==='r'?18:'auto',
            width: 26, height: 26, borderColor: 'var(--primary)', borderStyle: 'solid',
            borderWidth: `${k[0]==='t'?3:0}px ${k[1]==='r'?3:0}px ${k[0]==='b'?3:0}px ${k[1]==='l'?3:0}px`,
            borderTopLeftRadius: k==='tl'?8:0, borderTopRightRadius: k==='tr'?8:0, borderBottomLeftRadius: k==='bl'?8:0, borderBottomRightRadius: k==='br'?8:0 }} />
        ))}

        {phase === 'scanning' && (
          <div style={{ position: 'absolute', left: '6%', right: '6%', height: 3, borderRadius: 9,
            background: 'var(--primary)', boxShadow: '0 0 16px 3px var(--primary)', animation: 'taScan 1.8s ease-in-out infinite' }} />
        )}
        {phase === 'done' && (
          <div className="ta-pop" style={{ position: 'absolute', inset: 0, background: 'rgba(8,11,15,0.55)', backdropFilter: 'blur(3px)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, color: '#fff' }}>
            <div style={{ width: 64, height: 64, borderRadius: 99, background: 'var(--primary)', color: 'var(--on-primary)',
              display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconCheck s={36} /></div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19 }}>Receipt scanned</div>
            <div style={{ fontSize: 13, opacity: 0.8 }}>{SAMPLE_RECEIPT.items.length} items · taking you to assign…</div>
          </div>
        )}
      </div>

      <div style={{ padding: '0 18px 16px' }}>
        {phase === 'aim' && <>
          <div style={{ textAlign: 'center', fontSize: 13.5, color: 'var(--on-surface-var)', marginBottom: 12 }}>Line up the receipt inside the frame</div>
          <Button onClick={() => setPhase('scanning')} leading={<IconCamera s={21} />}>Capture</Button>
        </>}
        {phase !== 'aim' && <div style={{ height: 56, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, color: 'var(--on-surface-var)', fontWeight: 700 }}>
          <span style={{ width: 18, height: 18, borderRadius: 99, border: '2.5px solid var(--outline)', borderTopColor: 'var(--primary)', display: 'inline-block', animation: 'taSpin .7s linear infinite' }} /> {phase === 'scanning' ? 'Reading items…' : 'Done'}
        </div>}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenHeader, Steps, HomeScreen, ScanScreen });
