// ReturnScribe — Inbox · Subs · Refunds · Settings tabs (interactive)

// ─────────────────────────────────────────────────────────────
// INBOX
// ─────────────────────────────────────────────────────────────
function InboxScreen({ t, nav }) {
  const [filter, setFilter] = React.useState('all');
  const filters = [
    { id: 'all',         label: 'All',         count: RSData.inbox.length },
    { id: 'returnable',  label: 'Returnable' },
    { id: 'in-flight',   label: 'In Flight' },
    { id: 'refunded',    label: 'Refunded' },
    { id: 'closing',     label: 'Closing' },
  ];
  const filtered = filter === 'all' ? RSData.inbox
    : RSData.inbox.filter(p => p.status === filter);

  return (
    <div>
      {/* Search only — sliders/filter button removed */}
      <NavTitle t={t} title="Inbox"
        trailing={<button style={iconBtn(t)}><Icon name="magnifyingglass" size={20} color={t.text1}/></button>}/>
      <AnimatedFilterPills t={t} items={filters} active={filter} onChange={setFilter}/>

      <Card t={t} padding={0} style={{ margin: '0 16px' }}>
        {filtered.length === 0 ? (
          <EmptyState t={t} icon="tray" title="Nothing here"
            subtitle="Try a different filter, or connect a mailbox in Settings → Mailboxes"/>
        ) : (
          filtered.map((p, i) => (
            <CardPress key={p.id} onClick={() => nav.push('purchase', { purchase: p })}>
              <ListRow t={t}
                leading={<MerchantLogo name={p.merchant} cat={p.cat} t={t} size={40}/>}
                title={p.merchant}
                subtitle={p.item + ' · ' + p.when}
                trailing={<span>${p.amount.toFixed(2)}</span>}
                trailingSub={statusText(p.status, t)}
                chevron
                isLast={i === filtered.length - 1}
              />
            </CardPress>
          ))
        )}
      </Card>
      <div style={{ height: 16 }}/>
    </div>
  );
}

function EmptyState({ t, icon = 'tray', title, subtitle, action }) {
  return (
    <div style={{ padding: '56px 24px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, textAlign: 'center' }}>
      <Icon name={icon} size={40} color={t.text3} weight={1.6}/>
      <div style={{ color: t.text1, ...applyType(RSType.headline), marginTop: 4 }}>{title}</div>
      <div style={{ color: t.text2, ...applyType(RSType.subhead), maxWidth: 260 }}>{subtitle}</div>
      {action}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SUBSCRIPTIONS — rows tappable, no header "+", "Add subscription" row
// ─────────────────────────────────────────────────────────────
function SubsScreen({ t, nav }) {
  const [filter, setFilter] = React.useState('active');
  const filters = [
    { id: 'active',    label: 'Active' },
    { id: 'trial',     label: 'Trial' },
    { id: 'cancelled', label: 'Cancelled' },
  ];
  const groups = RSData.subs.groups
    .map(g => ({ ...g, items: g.items.filter(it =>
      filter === 'active'    ? it.kind === 'active' :
      filter === 'trial'     ? it.kind === 'trial' :
      filter === 'cancelled' ? it.kind === 'cancelled' : true
    )}))
    .filter(g => g.items.length > 0);

  return (
    <div>
      <NavTitle t={t} title="Subscriptions"/>

      <div style={{ padding: '4px 20px 20px' }}>
        <div style={{ color: t.text2, ...applyType(RSType.footnote), textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 600 }}>
          You're spending
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 6, ...RSTabular }}>
          <Money value={RSData.subs.monthly} size={44} color={t.text1}/>
          <span style={{ color: t.text2, ...applyType(RSType.callout) }}>/ month</span>
        </div>
        <div style={{ color: t.text3, ...applyType(RSType.footnote), marginTop: 4, ...RSTabular }}>
          ${RSData.subs.annual.toLocaleString('en-US', { minimumFractionDigits: 2 })} annualized · {RSData.subs.activeCount} active
        </div>
      </div>

      <AnimatedFilterPills t={t} items={filters} active={filter} onChange={setFilter}/>

      {groups.map(g => (
        <div key={g.freq} style={{ marginBottom: 12 }}>
          <SectionHead t={t} title={g.freq}/>
          <Card t={t} padding={0} style={{ margin: '0 16px' }}>
            {g.items.map((s, i) => (
              <CardPress key={s.id} onClick={() => nav.push('sub', { sub: s })}>
                <ListRow t={t}
                  leading={<MerchantLogo name={s.name} cat={s.cat} t={t} size={40}/>}
                  title={s.name}
                  subtitle={
                    s.kind === 'trial'
                      ? <span style={{ color: t.warning }}>Trial ends in {s.trialDaysLeft}d · then ${s.price}/mo</span>
                      : s.kind === 'cancelled'
                        ? <span>{s.next}</span>
                        : <span>Renews {s.next}</span>
                  }
                  trailing={<span>${s.price.toFixed(2)}</span>}
                  trailingSub={
                    s.kind === 'cancelled'
                      ? <StatusBadge label="CANCELLED" color={t.text3}/>
                      : <span style={{ color: t.text3, ...applyType(RSType.caption) }}>{s.cadence === 'yearly' ? '/yr' : '/mo'}</span>
                  }
                  chevron
                  isLast={i === g.items.length - 1}
                />
              </CardPress>
            ))}
          </Card>
        </div>
      ))}

      {/* Add subscription entry */}
      <div style={{ padding: '0 16px 8px' }}>
        <CardPress onClick={() => nav.openSheet('addSub')}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
            borderRadius: 14, background: t.surface1, border: `1px dashed ${t.borderStrong}`,
          }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, background: t.accentDim, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="plus" size={18} color={t.accent} weight={2.4}/>
            </div>
            <span style={{ color: t.accent, ...applyType(RSType.headline) }}>Add subscription</span>
          </div>
        </CardPress>
      </div>
      <div style={{ height: 16 }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// REFUNDS
// ─────────────────────────────────────────────────────────────
function RefundsScreen({ t, nav }) {
  const [filter, setFilter] = React.useState('flight');
  const filters = [
    { id: 'flight',    label: 'In flight', count: 4 },
    { id: 'completed', label: 'Completed' },
    { id: 'failed',    label: 'Failed' },
  ];

  function openRefund(r) {
    const p = RSData.inbox.find(x => x.merchant === r.merchant) || {
      id: r.id, merchant: r.merchant, item: r.item, amount: r.amount, currency: 'USD',
      purchaseDate: '—', returnBy: '—', windowDaysLeft: 0, windowTotal: 0, status: 'in-flight',
      refundType: 'Original payment', orderId: '—', payment: '—', source: '—', cat: r.cat,
      items: [{ name: r.item, qty: 1, unit: r.amount }],
    };
    nav.push('purchase', { purchase: p });
  }

  return (
    <div>
      <NavTitle t={t} title="Refunds"/>

      <div style={{ padding: '4px 20px 20px' }}>
        <div style={{ color: t.text2, ...applyType(RSType.footnote), textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 600 }}>
          In flight
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 6 }}>
          <Money value={606} size={44} color={t.accent}/>
          <span style={{ color: t.text2, ...applyType(RSType.callout) }}>expected · 4 refunds</span>
        </div>
      </div>

      <AnimatedFilterPills t={t} items={filters} active={filter} onChange={setFilter}/>

      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {RSData.refunds.map((r, i) => (
          <CardPress key={r.id} onClick={() => openRefund(r)}>
            <RefundCard t={t} r={r} reveal={i * 60}/>
          </CardPress>
        ))}
      </div>
      <div style={{ height: 16 }}/>
    </div>
  );
}

function RefundCard({ t, r, reveal = 0 }) {
  const tone = r.status === 'PROCESSING' ? t.success : t.accent;
  const steps = ['Initiated', 'Shipped', 'Received', 'Refunded'];
  const [fillPct, setFillPct] = React.useState(0);
  React.useEffect(() => {
    const id = setTimeout(() => setFillPct(r.step / r.total), 280 + reveal);
    return () => clearTimeout(id);
  }, [r.step, r.total, reveal]);
  return (
    <Card t={t} padding={18}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <MerchantLogo name={r.merchant} cat={r.cat} t={t} size={42}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
            <div style={{ color: t.text1, ...applyType(RSType.headline) }}>{r.merchant}</div>
            <div style={{ color: t.text1, ...applyType(RSType.headline), ...RSTabular }}>${r.amount.toFixed(2)}</div>
          </div>
          <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.item}</div>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, marginBottom: 8 }}>
        <StatusBadge label={r.status} color={tone}/>
        <span style={{ color: t.text3, ...applyType(RSType.footnote) }}>Day {r.days}</span>
      </div>

      <div style={{ position: 'relative', height: 3, borderRadius: 2, background: t.border, marginTop: 6, overflow: 'hidden' }}>
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: (fillPct * 100) + '%', background: tone, borderRadius: 2, transition: 'width 700ms cubic-bezier(.22,.61,.36,1)' }}/>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', gap: 4 }}>
          {steps.map((_, i) => i < steps.length - 1 && (
            <div key={i} style={{ flex: 1, borderRight: `2px solid ${RSTokens.dark === t ? '#1A1B1D' : '#FFFFFF'}` }}/>
          ))}
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
        {steps.map((label, i) => (
          <span key={i} style={{ color: i < r.step ? t.text2 : t.text3, ...applyType(RSType.caption), fontWeight: i < r.step ? 600 : 500 }}>{label}</span>
        ))}
      </div>
    </Card>
  );
}

// ─────────────────────────────────────────────────────────────
// SETTINGS
// ─────────────────────────────────────────────────────────────
function SettingsScreen({ t, dark, themeMode, onThemeChange, nav }) {
  const a = RSData.account;
  const [themeMenu, setThemeMenu] = React.useState(false);
  return (
    <div>
      <NavTitle t={t} title="Settings"
        trailing={
          <button onClick={() => setThemeMenu(true)} style={iconBtn(t)}>
            <Icon name={dark ? 'sun' : 'moon'} size={20} color={t.text1}/>
          </button>
        }/>
      <ThemeMenu t={t} open={themeMenu} onClose={() => setThemeMenu(false)} themeMode={themeMode} onThemeChange={onThemeChange}/>

      {/* Current plan card (Max) */}
      <div style={{ padding: '0 16px' }}>
        <CardPress onClick={() => nav.openModal('paywall')}>
          <div style={{
            position: 'relative', overflow: 'hidden', borderRadius: 16, padding: 18,
            border: `1px solid ${t.accent}`, background: t.surface1,
          }}>
            <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(120deg, ${t.accent}14, transparent 70%)` }}/>
            <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: t.accentDim, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="sparkles" size={20} color={t.accent}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ color: t.text1, ...applyType(RSType.headline) }}>ReturnScribe Max</div>
                <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 2 }}>Unlimited mailboxes · 120-day history</div>
              </div>
              <Icon name="chevron.right" size={15} color={t.text3} weight={2.2}/>
            </div>
          </div>
        </CardPress>
      </div>

      <SettingsGroup t={t} header="Subscription">
        <ChevronRow t={t} icon="sparkles" iconColor={t.accent} title="Manage subscription" subtitle="Max · renews Jul 12" onClick={() => nav.openModal('paywall')}/>
        <ChevronRow t={t} icon="arrow.triangle.2" iconColor={t.warning} title="Switch to Pro" subtitle="Downgrade at next renewal" onClick={() => nav.openSheet('downgrade')}/>
        <ChevronRow t={t} icon="arrow.down.left" title="Restore purchases" onClick={() => {}} isLast/>
      </SettingsGroup>

      <SettingsGroup t={t} header="Data">
        <ChevronRow t={t} icon="envelope" iconColor={t.accent} title="Mailboxes" trailing={`${a.mailboxes} connected`} onClick={() => {}}/>
        <ChevronRow t={t} icon="arrow.up.right" iconColor={t.success} title="Export my data" subtitle="JSON or CSV" onClick={() => nav.openSheet('export')} isLast/>
      </SettingsGroup>

      <SettingsGroup t={t} header="Privacy & Security">
        <ChevronRow t={t} icon="shield" title="Privacy" onClick={() => {}}/>
        <ChevronRow t={t} icon="lock" title="Security" subtitle="Face ID enabled" onClick={() => {}} isLast/>
      </SettingsGroup>

      <SettingsGroup t={t} header="Legal">
        <ChevronRow t={t} icon="doc" title="Privacy Policy" onClick={() => {}}/>
        <ChevronRow t={t} icon="doc" title="Terms of Use" onClick={() => {}} isLast/>
      </SettingsGroup>

      <SettingsGroup t={t} header="Account">
        <ChevronRow t={t} icon="house" title={a.name} subtitle={a.email} onClick={() => {}}/>
        <SettingsRow t={t} title="Sign out" titleColor={t.danger} chevron={false}/>
        <SettingsRow t={t} title="Delete account" titleColor={t.danger} chevron={false} isLast/>
      </SettingsGroup>

      <div style={{ textAlign: 'center', color: t.text3, ...applyType(RSType.caption), padding: '24px 0 12px' }}>
        ReturnScribe 2.0.0 (140)
      </div>
    </div>
  );
}

function SettingsGroup({ t, header, children }) {
  return (
    <div style={{ marginTop: 24 }}>
      {header && (
        <div style={{
          color: t.text2, ...applyType(RSType.footnote),
          textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 600, padding: '0 32px 8px',
        }}>{header}</div>
      )}
      <Card t={t} padding={0} style={{ margin: '0 16px' }}>{children}</Card>
    </div>
  );
}

function SettingsRow({ t, icon, title, subtitle, trailing, chevron = true, isLast, titleColor, onClick }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', minHeight: 52, position: 'relative',
      cursor: onClick ? 'pointer' : 'default',
    }}>
      {icon && (
        <div style={{ width: 30, height: 30, borderRadius: 8, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={icon} size={17} color={t.text1}/>
        </div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ color: titleColor || t.text1, ...applyType(RSType.body) }}>{title}</div>
        {subtitle && <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 1 }}>{subtitle}</div>}
      </div>
      {trailing && <span style={{ color: t.text2, ...applyType(RSType.subhead) }}>{trailing}</span>}
      {chevron && <Icon name="chevron.right" size={14} color={t.text3} weight={2.2}/>}
      {!isLast && <div style={{ position: 'absolute', left: icon ? 58 : 16, right: 16, bottom: 0, height: 0.5, background: t.border }}/>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// DATA EXPORT SHEET (share-sheet style)
// ─────────────────────────────────────────────────────────────
function DataExportSheet({ t, open, onClose }) {
  const [format, setFormat] = React.useState('json');
  return (
    <Sheet t={t} open={open} onClose={onClose} title="Export my data">
      <div style={{ padding: '8px 24px 4px', textAlign: 'center' }}>
        <div style={{ width: 52, height: 52, borderRadius: 14, margin: '0 auto 12px', background: t.success + '1A', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="arrow.up.right" size={26} color={t.success}/>
        </div>
        <p style={{ color: t.text2, ...applyType(RSType.callout), lineHeight: 1.5, margin: 0 }}>
          Download everything ReturnScribe has parsed — purchases, subscriptions, refunds and receipts.
        </p>
      </div>
      <div style={{ padding: '18px 16px 4px' }}>
        <BigSegmented t={t} active={format} onChange={setFormat}
          items={[{ id: 'json', label: 'JSON' }, { id: 'csv', label: 'CSV' }]}/>
        <div style={{ padding: '12px 8px 0', color: t.text3, ...applyType(RSType.caption), textAlign: 'center' }}>
          {format === 'json' ? 'Full structured export incl. line items.' : 'Spreadsheet-friendly, one row per purchase.'}
        </div>
      </div>
      <div style={{ padding: '18px 16px 8px' }}>
        <PressScale>
          <Button t={t} kind="primary" icon={<Icon name="arrow.up.right" size={18} color="#fff"/>} onClick={onClose}>
            Export &amp; share ({format.toUpperCase()})
          </Button>
        </PressScale>
      </div>
    </Sheet>
  );
}

Object.assign(window, {
  InboxScreen, SubsScreen, RefundsScreen, SettingsScreen,
  EmptyState, RefundCard, SettingsGroup, SettingsRow, DataExportSheet,
});
