// ReturnScribe — Subscription detail + edit + add

// ─────────────────────────────────────────────────────────────
// SUBSCRIPTION DETAIL (pushed)
// ─────────────────────────────────────────────────────────────
function SubscriptionDetailScreen({ t, sub, nav }) {
  const [menu, setMenu] = React.useState(false);
  const [editing, setEditing] = React.useState(false);
  const [stopping, setStopping] = React.useState(false);
  const [s, setS] = React.useState(sub);

  const cadenceLabel = s.cadence === 'yearly' ? '/ year' : '/ month';
  const monthly = s.cadence === 'yearly' ? s.price / 12 : s.price;

  return (
    <div style={{ position: 'relative', minHeight: '100%' }}>
      <NavBar t={t} title="" onBack={() => nav.pop()}
        trailing={
          <button onClick={() => setMenu(true)} style={iconBtn(t)}>
            <Icon name="ellipsis" size={20} color={t.text1}/>
          </button>
        }/>

      {/* Header */}
      <div style={{ padding: '8px 24px 22px', display: 'flex', alignItems: 'center', gap: 16 }}>
        <MerchantLogo name={s.name} cat={s.cat} t={t} size={60}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ color: t.text1, ...applyType(RSType.title2) }}>{s.name}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
            <span style={{ color: t.text1, fontFamily: RSFont.num, fontSize: 26, fontWeight: 700, ...RSTabular }}>
              ${s.price.toFixed(2)}
            </span>
            <span style={{ color: t.text2, ...applyType(RSType.subhead) }}>{cadenceLabel}</span>
          </div>
        </div>
      </div>

      {/* Trial banner */}
      {s.kind === 'trial' && (
        <div style={{ padding: '0 16px 16px' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 14,
            background: t.warning + '1A', border: `0.5px solid ${t.warning}40`,
          }}>
            <Icon name="clock" size={22} color={t.warning}/>
            <div style={{ flex: 1 }}>
              <div style={{ color: t.text1, ...applyType(RSType.headline) }}>Trial ends in {s.trialDaysLeft} days</div>
              <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 1 }}>
                You’ll be charged ${s.price.toFixed(2)} on {s.next}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Details */}
      <SectionHead t={t} title="Details"/>
      <Card t={t} padding={0} style={{ margin: '0 16px' }}>
        <DetailRow t={t} label="Service" value={s.name}/>
        <DetailRow t={t} label="Price" value={`$${s.price.toFixed(2)}`} tabular/>
        <DetailRow t={t} label="Billing" value={s.cadence === 'yearly' ? 'Yearly' : 'Monthly'}/>
        <DetailRow t={t} label={s.kind === 'cancelled' ? 'Status' : 'Next renewal'} value={s.kind === 'cancelled' ? s.next : s.next}/>
        {s.kind === 'trial'
          ? <DetailRow t={t} label="Trial ends" value={`in ${s.trialDaysLeft} days`} isLast/>
          : <DetailRow t={t} label="Tracking since" value={s.started} isLast/>}
      </Card>

      {/* Cost insight */}
      {s.cadence === 'yearly' && (
        <div style={{ padding: '12px 20px 0' }}>
          <span style={{ color: t.text3, ...applyType(RSType.footnote) }}>
            ≈ ${monthly.toFixed(2)} / month · ${(s.price).toFixed(2)} / year
          </span>
        </div>
      )}

      {/* Stop tracking */}
      <div style={{ padding: '24px 16px 0' }}>
        <CardPress onClick={() => setStopping(true)}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
            borderRadius: 14, background: t.surface1, border: `0.5px solid ${t.border}`,
          }}>
            <Icon name="xmark" size={20} color={t.danger}/>
            <div style={{ flex: 1 }}>
              <div style={{ color: t.danger, ...applyType(RSType.headline) }}>Stop tracking in ReturnScribe</div>
              <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 2 }}>
                Removes it from this app only — your real subscription stays active.
              </div>
            </div>
          </div>
        </CardPress>
      </div>

      <div style={{ height: 24 }}/>

      <ActionMenu t={t} open={menu} onClose={() => setMenu(false)} items={[
        { label: 'Edit', icon: 'sliders', onClick: () => setEditing(true) },
        { label: 'Stop tracking', icon: 'xmark', danger: true, onClick: () => setStopping(true) },
      ]}/>

      <SubEditSheet t={t} open={editing} onClose={() => setEditing(false)} sub={s} onSave={setS}/>

      {/* Stop-tracking confirm */}
      <Sheet t={t} open={stopping} onClose={() => setStopping(false)} title="Stop tracking?">
        <div style={{ padding: '16px 24px 8px', textAlign: 'center' }}>
          <p style={{ color: t.text2, ...applyType(RSType.callout), lineHeight: 1.5 }}>
            <b style={{ color: t.text1 }}>{s.name}</b> will be removed from ReturnScribe. This only stops
            tracking inside the app — it does <b style={{ color: t.text1 }}>not</b> cancel your real
            subscription with the provider.
          </p>
        </div>
        <div style={{ padding: '12px 16px 8px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <PressScale>
            <Button t={t} kind="primary" style={{ background: t.danger }}
              onClick={() => { setStopping(false); nav.pop(); }}>
              Stop tracking
            </Button>
          </PressScale>
          <button onClick={() => setStopping(false)} style={{
            background: 'none', border: 'none', cursor: 'pointer', color: t.accent,
            ...applyType(RSType.headline), padding: 10,
          }}>Keep tracking</button>
        </div>
      </Sheet>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SUB EDIT SHEET (also reused for Add)
// ─────────────────────────────────────────────────────────────
function SubEditSheet({ t, open, onClose, sub, onSave, isNew }) {
  const [draft, setDraft] = React.useState(sub);
  const [picker, setPicker] = React.useState(null); // 'cadence'
  const orig = React.useRef(sub);
  React.useEffect(() => { if (open) { setDraft(sub); orig.current = sub; } }, [open]);

  const set = (k, v) => setDraft(d => ({ ...d, [k]: v }));
  const edited = (k) => !isNew && draft[k] !== orig.current[k];

  return (
    <Sheet t={t} open={open} onClose={onClose} title={isNew ? 'Add subscription' : 'Edit subscription'}
      trailing={
        <button onClick={() => { onSave(draft); onClose(); }} style={{
          background: 'none', border: 'none', cursor: 'pointer', color: t.accent, ...applyType(RSType.headline),
        }}>{isNew ? 'Add' : 'Save'}</button>
      }>
      <div style={{ padding: '12px 0 4px' }}>
        <Card t={t} padding={0} style={{ margin: '0 16px' }}>
          <Field t={t} label="Service" value={draft.name} onChange={v => set('name', v)} placeholder="e.g. Netflix" edited={edited('name')}/>
          <Field t={t} label="Price" value={String(draft.price)} prefix="$" type="number"
            onChange={v => set('price', parseFloat(v) || 0)} edited={edited('price')}/>
          <Field t={t} label="Billing" value={draft.cadence === 'yearly' ? 'Yearly' : 'Monthly'}
            options onPick={() => setPicker('cadence')} edited={edited('cadence')}/>
          <Field t={t} label="Next renewal" value={draft.next} onChange={v => set('next', v)} edited={edited('next')}/>
          <Field t={t} label="Trial ends" value={draft.trialDaysLeft ? `${draft.trialDaysLeft} days` : 'None'}
            onChange={v => set('trialDaysLeft', parseInt(v) || 0)} isLast edited={edited('trialDaysLeft')}/>
        </Card>
        <div style={{ padding: '12px 28px 0', color: t.text3, ...applyType(RSType.footnote), lineHeight: 1.4 }}>
          Editing here only changes how ReturnScribe tracks this subscription. It doesn’t affect billing.
        </div>
      </div>

      <PickerSheet t={t} open={picker === 'cadence'} onClose={() => setPicker(null)}
        title="Billing cycle" value={draft.cadence === 'yearly' ? 'Yearly' : 'Monthly'}
        options={['Monthly', 'Yearly']}
        onPick={v => set('cadence', v.toLowerCase())}/>
    </Sheet>
  );
}

Object.assign(window, { SubscriptionDetailScreen, SubEditSheet });
