// ReturnScribe v3 "Ledger" — Home screen
// Ledger hero (ruled lines, mono numerals) · deadline ticket rail · ledger entries

// ─────────────────────────────────────────────────────────────
// Hero — the ledger summary block. Rotates between 3 states;
// arrows + dots to switch manually, tap to pause.
// ─────────────────────────────────────────────────────────────
function HeroCounter({ t }) {
  const states = RSData.heroStates;
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setIdx(i => (i + 1) % states.length), 6000);
    return () => clearInterval(id);
  }, [paused, states.length]);

  const state = states[idx];
  const toneColor = state.tone === 'success' ? t.success
                  : state.tone === 'warning' ? t.warning
                  : t.accent;

  return (
    <div onClick={() => setPaused(p => !p)} style={{ margin: '0 20px', cursor: 'pointer' }}>
      {/* Ruled ledger block — top double rule, bottom single rule */}
      <div style={{ borderTop: `3px double ${t.borderStrong}`, paddingTop: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span key={state.key + '-label'} style={{
            color: t.text2, ...applyMono(RSType.eyebrow), textTransform: 'uppercase', whiteSpace: 'nowrap',
            overflow: 'hidden', textOverflow: 'ellipsis',
            animation: 'rsFadeIn 380ms ease',
          }}>{state.label}</span>
          <span style={{ color: t.text3, ...applyMono(RSType.caption), whiteSpace: 'nowrap', flexShrink: 0, marginLeft: 10 }}>
            {paused ? '⏸ HELD' : `No. ${String(idx + 1).padStart(2, '0')}/03`}
          </span>
        </div>

        <div style={{ marginTop: 12, minHeight: 76 }}>
          <FluidMoney value={state.amount} size={58} color={toneColor} weight={500}/>
          <div key={state.key} style={{
            color: t.text2, ...applyDisp(RSType.callout, { fontStyle: 'italic', fontSize: 16 }),
            marginTop: 6, animation: 'rsFadeIn 380ms cubic-bezier(.2,.7,.3,1)',
          }}>{state.caption}</div>
        </div>

        {/* control row sits on the bottom rule */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          borderBottom: `1px solid ${t.borderStrong}`, paddingBottom: 10, marginTop: 12,
        }}>
          <button
            onClick={(e) => { e.stopPropagation(); setIdx((idx - 1 + states.length) % states.length); }}
            aria-label="Previous"
            style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 6, display: 'flex' }}>
            <Icon name="chevron.left" size={14} color={t.text2} weight={2.2}/>
          </button>
          <div style={{ display: 'flex', gap: 2 }}>
            {states.map((_, i) => (
              <button key={i}
                onClick={(e) => { e.stopPropagation(); setIdx(i); }}
                aria-label={`Go to ${i + 1}`}
                style={{
                  width: 26, height: 26, padding: 0, background: 'transparent',
                  border: 'none', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                <span style={{
                  display: 'block', width: 7, height: 7,
                  borderRadius: i === idx ? 1 : 99,
                  background: i === idx ? toneColor : 'transparent',
                  border: i === idx ? 'none' : `1px solid ${t.text3}`,
                  transform: i === idx ? 'rotate(45deg)' : 'none',
                  transition: 'all 280ms cubic-bezier(.2,.7,.3,1)',
                }}></span>
              </button>
            ))}
          </div>
          <button
            onClick={(e) => { e.stopPropagation(); setIdx((idx + 1) % states.length); }}
            aria-label="Next"
            style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 6, display: 'flex' }}>
            <Icon name="chevron.right" size={14} color={t.text2} weight={2.2}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Deadline ticket — tear-off stub with perforated left edge
// ─────────────────────────────────────────────────────────────
function DeadlineTicket({ t, d, onClick }) {
  const urgent = d.daysLeft <= 3;
  const tone = urgent ? t.warning : t.text2;
  return (
    <CardPress onClick={onClick}>
      <div style={{
        width: 188, flexShrink: 0, position: 'relative',
        background: t.surface1,
        borderTop: `1px solid ${t.borderStrong}`,
        borderRight: `1px solid ${t.borderStrong}`,
        borderBottom: `1px solid ${t.borderStrong}`,
        borderLeft: `1px dashed ${t.borderStrong}`,
        borderRadius: 8,
        boxShadow: t === RSTokens.dark ? '0 2px 0 rgba(0,0,0,0.28)' : `2px 2px 0 ${t.border}`,
        padding: '12px 14px 12px 18px',
      }}>
        {/* perforation notches */}
        <div style={{
          position: 'absolute', left: -6, top: '50%', transform: 'translateY(-50%)',
          width: 10, height: 10, borderRadius: 99, background: t.canvas,
          borderTop: '1px solid transparent',
          borderLeft: '1px solid transparent',
          borderRight: `1px solid ${t.borderStrong}`,
          borderBottom: `1px solid ${t.borderStrong}`,
          rotate: '45deg',
        }}></div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <MerchantLogo name={d.merchant} cat={d.cat} t={t} size={26}/>
          <span style={{ color: t.text1, ...applyType(RSType.footnote), fontWeight: 600, flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.merchant}</span>
        </div>
        <div style={{ marginTop: 10, display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span style={{ color: tone, ...applyMono(RSType.title1, { fontSize: 30, fontWeight: 500 }), ...RSTabular }}>{d.daysLeft}</span>
          <span style={{ color: tone, ...applyMono(RSType.caption), textTransform: 'uppercase', whiteSpace: 'nowrap' }}>days left</span>
        </div>
        <div style={{
          marginTop: 8, paddingTop: 8, borderTop: `1px dashed ${t.border}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        }}>
          <span style={{ color: t.text3, ...applyType(RSType.caption), whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 86 }}>{d.item}</span>
          <span style={{ color: t.text1, ...applyMono(RSType.caption), fontWeight: 600, ...RSTabular }}>${d.amount.toFixed(0)}</span>
        </div>
      </div>
    </CardPress>
  );
}

// ─────────────────────────────────────────────────────────────
// Home
// ─────────────────────────────────────────────────────────────
// Theme dropdown — System default / Light / Dark, anchored under the masthead button
function ThemeMenu({ t, open, onClose, themeMode, onThemeChange }) {
  return (
    <ActionMenu t={t} open={open} onClose={onClose} items={[
      { label: 'System default', icon: 'gear', selected: themeMode === 'system', onClick: () => onThemeChange('system') },
      { label: 'Light',          icon: 'sun',  selected: themeMode === 'light',  onClick: () => onThemeChange('light') },
      { label: 'Dark',           icon: 'moon', selected: themeMode === 'dark',   onClick: () => onThemeChange('dark') },
    ]}/>
  );
}

function HomeScreen({ t, dark, themeMode, onThemeChange, scrollRef, nav }) {
  const accent = t.accent;
  const [themeMenu, setThemeMenu] = React.useState(false);
  const today = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
  return (
    <div>
      {/* Masthead — editorial serif */}
      <div style={{ padding: '10px 20px 18px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ color: t.text3, ...applyMono(RSType.eyebrow), textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{today}</div>
          <h1 style={{ margin: '8px 0 0', color: t.text1, ...applyDisp(RSType.large), whiteSpace: 'nowrap' }}>
            The Ledger
          </h1>
          <div style={{ color: t.text2, ...applyDisp(RSType.callout, { fontStyle: 'italic' }), marginTop: 4, whiteSpace: 'nowrap' }}>
            {greeting()}
          </div>
        </div>
        <PressScale as="button" onClick={() => setThemeMenu(true)} style={iconBtn(t)}>
          <Icon name={dark ? 'sun' : 'moon'} size={19} color={t.text1}/>
        </PressScale>
      </div>
      <ThemeMenu t={t} open={themeMenu} onClose={() => setThemeMenu(false)} themeMode={themeMode} onThemeChange={onThemeChange}/>

      <HeroCounter t={t}/>

      {/* Deadline ticket rail */}
      <RevealOnScroll root={scrollRef} delay={40}>
        <SectionTitle t={t} label="Closing soon" count={3} color={t.warning}/>
        <div style={{
          display: 'flex', gap: 12, padding: '4px 20px 6px', overflowX: 'auto',
          WebkitOverflowScrolling: 'touch',
        }}>
          {RSData.deadlines.map((d, i) => (
            <DeadlineTicket key={i} t={t} d={d} onClick={() => nav.push('purchase', { purchase: resolvePurchase(d) })}/>
          ))}
        </div>
      </RevealOnScroll>

      {/* Counts strip — inline ledger figures, not tiles */}
      <RevealOnScroll root={scrollRef} delay={80}>
        <div style={{
          margin: '18px 20px 0', display: 'flex',
          border: `1px solid ${t.borderStrong}`, borderRadius: 8, overflow: 'hidden',
          background: t.surface1,
        }}>
          {[
            { n: 12, label: 'Returns', sub: 'tracked' },
            { n: 9, label: 'Subs', sub: '$247/mo' },
            { n: RSData.inFlight.count, label: 'In flight', sub: `$${RSData.inFlight.total.toFixed(0)} expected` },
          ].map((s, i) => (
            <div key={i} style={{
              flex: 1, padding: '12px 14px',
              borderLeft: i ? `1px dashed ${t.borderStrong}` : 'none',
            }}>
              <div style={{ color: t.text1, ...applyMono(RSType.title2, { fontWeight: 500 }), ...RSTabular }}>{s.n}</div>
              <div style={{ color: t.text2, ...applyMono(RSType.caption), textTransform: 'uppercase', marginTop: 3 }}>{s.label}</div>
              <div style={{ color: t.text3, ...applyType(RSType.caption), marginTop: 1 }}>{s.sub}</div>
            </div>
          ))}
        </div>
      </RevealOnScroll>

      {/* Connect banner — dashed "attach here" slot */}
      <RevealOnScroll root={scrollRef} delay={120}>
        <div style={{ padding: '14px 20px 0' }}>
          <ConnectBanner t={t}/>
        </div>
      </RevealOnScroll>

      {/* Recent entries — ledger rows with dotted leaders */}
      <RevealOnScroll root={scrollRef} delay={160}>
        <SectionTitle t={t} label="Recent entries"
          action={<span style={{ color: accent, ...applyMono(RSType.caption), fontWeight: 600, textTransform: 'uppercase' }}>All →</span>}/>
        <Card t={t} padding={0} style={{ margin: '0 20px' }}>
          {RSData.recent.map((r, i) => (
            <CardPress key={i} onClick={() => nav.push('purchase', { purchase: resolvePurchase(r) })}>
              <ListRow t={t}
                leading={<MerchantLogo name={r.merchant} cat={r.cat} t={t} size={38}/>}
                title={r.merchant}
                subtitle={r.item}
                trailing={<span>${r.amount.toFixed(2)}</span>}
                trailingSub={statusText(r.status, t)}
                chevron
                isLast={i === RSData.recent.length - 1}
              />
            </CardPress>
          ))}
        </Card>
      </RevealOnScroll>

      <div style={{ height: 20 }}/>
    </div>
  );
}

function statusText(status, t) {
  const map = {
    returnable: { label: 'RETURNABLE', color: t.accent },
    closing:    { label: 'CLOSING', color: t.warning },
    'in-flight':{ label: 'IN FLIGHT',  color: t.text2 },
    completed:  { label: 'REFUNDED',   color: t.success },
    refunded:   { label: 'REFUNDED',   color: t.success },
    'final-sale': { label: 'FINAL SALE', color: t.text3 },
    expired:    { label: 'EXPIRED',    color: t.text3 },
  };
  const s = map[status] || { label: status.toUpperCase(), color: t.text2 };
  return <StatusBadge label={s.label} color={s.color}/>;
}

function iconBtn(t) {
  return {
    width: 36, height: 36, borderRadius: 8,
    background: 'transparent', border: `1px solid ${t.borderStrong}`,
    cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
}

// ─────────────────────────────────────────────────────────────
// Connect-mailbox banner — dashed attach slot
// ─────────────────────────────────────────────────────────────
function ConnectBanner({ t }) {
  return (
    <CardPress onClick={() => {}}>
      <div style={{
        borderRadius: 8, padding: '14px 16px',
        border: `1.5px dashed ${t.borderStrong}`,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{
          width: 38, height: 38, borderRadius: 8, flexShrink: 0,
          border: `1px solid ${t.accent}55`, background: t.accentDim,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="envelope" size={19} color={t.accent}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ color: t.text1, ...applyType(RSType.headline) }}>Connect Gmail or Outlook</div>
          <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 2 }}>
            Auto-import receipts · read-only access
          </div>
        </div>
        <Icon name="chevron.right" size={15} color={t.text3} weight={2.2}/>
      </div>
    </CardPress>
  );
}

// Kept for API compat (no longer used on Home)
function BentoStat({ t, value, label, sub, icon, color }) {
  return (
    <div style={{
      flex: 1, padding: '14px 16px', borderRadius: 8,
      border: `1px solid ${t.borderStrong}`, background: t.surface1,
    }}>
      <div style={{ color: t.text1, ...applyMono(RSType.title2), ...RSTabular }}>{value}</div>
      <div style={{ color: t.text2, ...applyMono(RSType.caption), textTransform: 'uppercase', marginTop: 3 }}>{label}</div>
      {sub && <div style={{ color: t.text3, ...applyType(RSType.caption) }}>{sub}</div>}
    </div>
  );
}

function greeting() {
  const h = new Date().getHours();
  if (h < 12) return 'Good morning';
  if (h < 17) return 'Good afternoon';
  return 'Good evening';
}

Object.assign(window, { HomeScreen, HeroCounter, statusText, iconBtn, BentoStat, ConnectBanner, DeadlineTicket });
