// Subscription / Plans screen — three user states (free / monthly / annual)
// In-page DEV toggle lets you flip between states for review.

function SubscriptionScreen({ theme, accent, onBack, planState = 'free', setPlanState }) {
  const s = SUBSCRIPTION;
  const setState = setPlanState || (() => {});
  const [showCancel, setShowCancel] = React.useState(false);

  const annualMo  = s.pricePerMonth;          // 39
  const monthlyMo = s.monthlyPrice;           // 49
  const annualTotal = annualMo * 12;
  const yearlySavings = (monthlyMo - annualMo) * 12;

  // Free state needs a sticky bottom CTA, so disable the screen padding
  // and let FreeView own its layout.
  if (planState === 'free') {
    return (
      <div style={{ position: 'relative', height: '100%' }}>
        <FreeView theme={theme} accent={accent}
          monthlyMo={monthlyMo} annualMo={annualMo} annualTotal={annualTotal} yearlySavings={yearlySavings}
          onBack={onBack}
          onSubscribe={(cycle) => setState(cycle)}
          renderDevToggle={() => <DevStateToggle theme={theme} planState={planState} setPlanState={setState}/>}/>
      </div>
    );
  }

  return (
    <div style={{ position: 'relative', height: '100%' }}>
      <Screen theme={theme} padTop={0} padBottom={40}>
        <NavBar theme={theme} title="Plans" onBack={onBack}/>

        <DevStateToggle theme={theme} planState={planState} setPlanState={setState}/>

        {planState === 'monthly' && (
          <MonthlyView theme={theme} accent={accent}
            monthlyMo={monthlyMo} annualMo={annualMo}
            annualTotal={annualTotal} yearlySavings={yearlySavings}
            onSwitchToAnnual={() => setState('annual')}
            onCancel={() => setShowCancel(true)}/>
        )}
        {planState === 'annual' && (
          <AnnualView theme={theme} accent={accent} s={s} annualMo={annualMo}
            onCancel={() => setShowCancel(true)}/>
        )}
      </Screen>

      {showCancel && (
        <div style={{
          position: 'absolute', inset: 0, zIndex: 60,
          background: theme.bg,
        }}>
          <SubscriptionCancelScreen theme={theme} accent={accent}
            planTier={planState === 'annual' ? 'annual' : 'monthly'}
            onClose={() => setShowCancel(false)}
            onCancelled={() => setState('free')}/>
        </div>
      )}
    </div>
  );
}

// ───── Dev state toggle (free / monthly / annual) ─────
function DevStateToggle({ theme, planState, setPlanState }) {
  return (
    <div style={{ padding: '0 16px 4px' }}>
      <div style={{
        fontFamily: FONTS.mono, fontSize: 9, letterSpacing: 1.4, textTransform: 'uppercase',
        color: theme.textMute, padding: '0 4px 6px',
      }}>Dev · plan state</div>
      <div style={{
        display: 'flex', gap: 0,
        background: theme.surface2, borderRadius: 10, padding: 3,
      }}>
        {[
          { id: 'free',    label: 'Not subscribed' },
          { id: 'monthly', label: 'Monthly' },
          { id: 'annual',  label: 'Annual' },
        ].map(o => (
          <button key={o.id} onClick={() => setPlanState(o.id)} style={{
            flex: 1, padding: '8px 0',
            background: planState === o.id ? theme.surface : 'transparent',
            border: 'none', borderRadius: 8,
            color: planState === o.id ? theme.text : theme.textDim,
            fontFamily: FONTS.ui, fontSize: 11.5, fontWeight: planState === o.id ? 600 : 500,
            cursor: 'pointer',
            boxShadow: planState === o.id ? '0 1px 3px rgba(0,0,0,0.05)' : 'none',
          }}>{o.label}</button>
        ))}
      </div>
    </div>
  );
}

// ───── State 1 · Not subscribed (Careem-style sticky CTAs) ─────
function FreeView({ theme, accent, monthlyMo, annualMo, annualTotal, yearlySavings, onBack, onSubscribe, renderDevToggle }) {
  const [cycle, setCycle] = React.useState('annual'); // 'monthly' | 'annual'

  return (
    <>
      <Screen theme={theme} padTop={0} padBottom={230}>
        <NavBar theme={theme} title="Plans" onBack={onBack}/>
        {renderDevToggle && renderDevToggle()}

        {/* Hero */}
        <div style={{ padding: '14px 16px 0' }}>
          <Card theme={theme} padded={false} style={{
            padding: 22,
            background: `linear-gradient(155deg, ${accent}14, ${theme.surface} 90%)`,
            position: 'relative', overflow: 'hidden',
          }}>
            <svg width="180" height="180" style={{ position: 'absolute', top: -50, right: -50, opacity: 0.10 }}>
              <circle cx="90" cy="90" r="88" fill="none" stroke={accent} strokeWidth="0.5"/>
              <circle cx="90" cy="90" r="68" fill="none" stroke={accent} strokeWidth="0.5"/>
              <circle cx="90" cy="90" r="48" fill="none" stroke={accent} strokeWidth="0.5"/>
            </svg>
            <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1.4, textTransform: 'uppercase', color: accent, marginBottom: 8 }}>
              Start saving today
            </div>
            <div style={{ fontFamily: FONTS.display, fontSize: 28, color: theme.text, letterSpacing: -0.6, lineHeight: 1.1 }}>
              Himma Pro
            </div>
            <div style={{ fontSize: 13, color: theme.textDim, marginTop: 8, lineHeight: 1.5 }}>
              Every asset class · unlimited AI · personalised recommendations.
            </div>
          </Card>
        </div>

        {/* Benefits */}
        <div style={{ padding: '22px 16px 0' }}>
          <SectionLabel theme={theme} style={{ padding: '0 4px 10px' }}>What you get</SectionLabel>
          <Card theme={theme} padded={false} style={{ padding: 16 }}>
            {PLAN_BENEFITS_PRO.map((b, i) => {
              const Icon = Ico[b.icon] || Ico.check;
              return (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '9px 0',
                  borderBottom: i === PLAN_BENEFITS_PRO.length - 1 ? 'none' : `0.5px solid ${theme.line}`,
                }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 8,
                    background: `${accent}18`, color: accent,
                    display:'flex', alignItems:'center', justifyContent:'center',
                    flexShrink: 0,
                  }}><Icon size={14}/></div>
                  <span style={{ fontSize: 13, color: theme.text, lineHeight: 1.4 }}>{dhText(b.text)}</span>
                </div>
              );
            })}
          </Card>
        </div>
      </Screen>

      {/* Sticky bottom: monthly/annual cards + Subscribe CTA */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        padding: '14px 16px 30px',
        background: theme.bg,
        borderTop: `0.5px solid ${theme.line}`,
        boxShadow: '0 -10px 30px rgba(0,0,0,0.06)',
      }}>
        <div style={{
          fontFamily: FONTS.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase',
          color: theme.textMute, textAlign: 'center', marginBottom: 10,
        }}>Choose your plan</div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 12 }}>
          <CycleCard
            theme={theme} accent={accent}
            selected={cycle === 'monthly'}
            onSelect={() => setCycle('monthly')}
            label="Monthly"
            tag="Popular" tagIcon
            price={<><Dh/> {monthlyMo}</>}
            sub="/month"/>
          <CycleCard
            theme={theme} accent={accent}
            selected={cycle === 'annual'}
            onSelect={() => setCycle('annual')}
            label="Annual"
            tag={<>Save <Dh/> {yearlySavings}</>}
            price={<><Dh/> {annualMo}</>}
            sub={<>/month · <Dh/> {annualTotal} billed yearly</>}/>
        </div>

        <button onClick={() => onSubscribe(cycle)} style={{
          width: '100%',
          background: accent, color: '#fff',
          border: 'none', borderRadius: 16,
          padding: '15px',
          fontFamily: FONTS.ui, fontSize: 14, fontWeight: 600,
          cursor: 'pointer',
        }}>Subscribe now</button>
        <div style={{ textAlign: 'center', marginTop: 8, fontSize: 11, color: theme.textMute }}>
          You can cancel anytime
        </div>
      </div>
    </>
  );
}

function CycleCard({ theme, accent, selected, onSelect, label, tag, tagIcon, price, sub }) {
  return (
    <button onClick={onSelect} style={{
      textAlign: 'left',
      background: selected ? theme.surface : theme.surface2,
      border: `${selected ? 1.5 : 0.5}px solid ${selected ? accent : theme.line2}`,
      borderRadius: 14,
      padding: '12px 12px',
      cursor: 'pointer',
      color: theme.text,
      position: 'relative',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: theme.text }}>{label}</span>
        {tag && (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 3,
            fontSize: 9.5, fontWeight: 600, letterSpacing: 0.3,
            padding: '2px 6px', borderRadius: 4,
            background: `${accent}1c`, color: accent,
            fontFamily: FONTS.ui,
          }}>
            {tagIcon && <Ico.bolt size={9} sw={2}/>}
            {tag}
          </span>
        )}
      </div>
      <div style={{ fontSize: 12.5, color: theme.text, marginTop: 6, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
        {price}
        <span style={{ fontSize: 11, color: theme.textDim, fontWeight: 400 }}>{sub}</span>
      </div>
    </button>
  );
}

// ───── Plan card (shared shell — used by Monthly state) ─────
function PlanCard({ theme, accent, title, statusTag, statusColor, priceLine }) {
  return (
    <div style={{ padding: '14px 16px 0' }}>
      <Card theme={theme} padded={false} style={{
        padding: 22,
        background: `linear-gradient(155deg, ${accent}10, ${theme.surface} 90%)`,
        position: 'relative', overflow: 'hidden',
      }}>
        <svg width="180" height="180" style={{ position: 'absolute', top: -50, right: -50, opacity: 0.10 }}>
          <circle cx="90" cy="90" r="88" fill="none" stroke={accent} strokeWidth="0.5"/>
          <circle cx="90" cy="90" r="68" fill="none" stroke={accent} strokeWidth="0.5"/>
          <circle cx="90" cy="90" r="48" fill="none" stroke={accent} strokeWidth="0.5"/>
        </svg>

        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap: 8 }}>
          <div style={{ fontFamily: FONTS.display, fontSize: 26, color: theme.text, letterSpacing: -0.5 }}>{title}</div>
          {statusTag && (
            <Tag theme={theme} color={statusColor} style={{ background: `${statusColor}14`, border: 'none', whiteSpace:'nowrap' }}>
              <span style={{ width: 6, height: 6, borderRadius: 3, background: statusColor, marginRight: 4, display: 'inline-block' }}/>
              {statusTag}
            </Tag>
          )}
        </div>

        <div style={{ marginTop: 12, fontFamily: FONTS.ui, fontSize: 14, color: theme.text, fontVariantNumeric: 'tabular-nums' }}>
          {priceLine}
        </div>
      </Card>
    </div>
  );
}

// ───── State 2 · Subscribed monthly ─────
function MonthlyView({ theme, accent, monthlyMo, annualMo, annualTotal, yearlySavings, onSwitchToAnnual, onCancel }) {
  return (
    <>
      <PlanCard theme={theme} accent={accent}
        title="Himma Pro · Monthly"
        statusTag="Active" statusColor={accent}
        priceLine={<><Dh/> {monthlyMo} /month · billed monthly</>}/>

      {/* Annual upsell */}
      <div style={{ padding: '14px 16px 0' }}>
        <Card theme={theme} padded={false} style={{
          padding: 18,
          background: `linear-gradient(155deg, ${accent}18, ${accent}06 90%)`,
          border: `0.5px solid ${accent}40`,
        }}>
          <div style={{
            display: 'inline-block',
            fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1.4, textTransform: 'uppercase',
            color: accent, padding: '4px 9px',
            background: `${accent}1f`, borderRadius: 999, marginBottom: 12,
          }}>Save 20%</div>
          <div style={{ fontFamily: FONTS.display, fontSize: 18, color: theme.text, lineHeight: 1.3 }}>
            Switch to annual and save <Dh/> {yearlySavings} per year
          </div>

          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14,
          }}>
            <PriceTile theme={theme} label="Current" amount={<><Dh/> {monthlyMo}</>} sub="/month"/>
            <PriceTile theme={theme} label="Annual"  amount={<><Dh/> {annualMo}</>}
              sub={<>/month · <Dh/> {annualTotal} billed yearly</>} highlight={accent}/>
          </div>

          <button onClick={onSwitchToAnnual} style={{
            marginTop: 14, width: '100%',
            background: accent, color: '#fff',
            border: 'none', borderRadius: 12,
            padding: '12px',
            fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600,
            cursor: 'pointer',
          }}>Switch to annual</button>
        </Card>
      </div>

      {/* Benefits — keep selling the value */}
      <BenefitsSection theme={theme} accent={accent} title="What's included"/>

      <PaymentMethodCard theme={theme} accent={accent}/>
      <CancelButton theme={theme} onCancel={onCancel}/>
    </>
  );
}

function PriceTile({ theme, label, amount, sub, highlight }) {
  return (
    <div style={{
      background: theme.surface,
      border: `0.5px solid ${highlight ? highlight + '50' : theme.line2}`,
      borderRadius: 12, padding: 12,
    }}>
      <div style={{
        fontFamily: FONTS.mono, fontSize: 9, letterSpacing: 1.2, textTransform: 'uppercase',
        color: highlight || theme.textMute, marginBottom: 6,
      }}>{label}</div>
      <div style={{ fontFamily: FONTS.display, fontSize: 18, color: theme.text, lineHeight: 1.1 }}>{amount}</div>
      <div style={{ fontSize: 10.5, color: theme.textDim, marginTop: 3, lineHeight: 1.35 }}>{sub}</div>
    </div>
  );
}

// ───── State 3 · Subscribed annual ─────
function AnnualView({ theme, accent, s, annualMo, onCancel }) {
  const monthsElapsed = 2;
  const cyclePct = (monthsElapsed / 12) * 100;

  return (
    <>
      <div style={{ padding: '14px 16px 0' }}>
        <Card theme={theme} padded={false} style={{
          padding: 22,
          background: `linear-gradient(155deg, ${accent}10, ${theme.surface} 90%)`,
          position: 'relative', overflow: 'hidden',
        }}>
          <svg width="180" height="180" style={{ position: 'absolute', top: -50, right: -50, opacity: 0.10 }}>
            <circle cx="90" cy="90" r="88" fill="none" stroke={accent} strokeWidth="0.5"/>
            <circle cx="90" cy="90" r="68" fill="none" stroke={accent} strokeWidth="0.5"/>
            <circle cx="90" cy="90" r="48" fill="none" stroke={accent} strokeWidth="0.5"/>
          </svg>

          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap: 8 }}>
            <div style={{ fontFamily: FONTS.display, fontSize: 26, color: theme.text, letterSpacing: -0.5 }}>Himma Pro · Annual</div>
            <Tag theme={theme} color={accent} style={{ background: `${accent}14`, border: 'none', whiteSpace:'nowrap' }}>
              <span style={{ width: 6, height: 6, borderRadius: 3, background: accent, marginRight: 4, display: 'inline-block' }}/>
              Active
            </Tag>
          </div>

          <div style={{ marginTop: 12, fontFamily: FONTS.ui, fontSize: 14, color: theme.text, fontVariantNumeric: 'tabular-nums' }}>
            <Dh/> {annualMo} /month · billed yearly
          </div>

          <div style={{ marginTop: 20 }}>
            <div style={{ display:'flex', justifyContent:'space-between', fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>
              <span>Started {s.startedOn}</span>
              <span>Renews {s.nextBilling}</span>
            </div>
            <div style={{ height: 5, borderRadius: 3, background: theme.surface3, overflow:'hidden' }}>
              <div style={{ width: `${cyclePct}%`, height: '100%', background: accent, borderRadius: 3 }}/>
            </div>
            <div style={{ fontSize: 11.5, color: theme.textDim, marginTop: 8 }}>
              {monthsElapsed} of 12 months used · next charge <Dh/> {fmtAED(s.renewsAmount)}
            </div>
          </div>
        </Card>
      </div>

      {/* Reaffirm value — show benefits */}
      <BenefitsSection theme={theme} accent={accent} title="What's included"/>

      <PaymentMethodCard theme={theme} accent={accent}/>
      <CancelButton theme={theme} onCancel={onCancel}/>
    </>
  );
}

// ───── Shared benefits list ─────
function BenefitsSection({ theme, accent, title }) {
  return (
    <div style={{ padding: '22px 16px 0' }}>
      <SectionLabel theme={theme} style={{ padding: '0 4px 10px' }}>{title}</SectionLabel>
      <Card theme={theme} padded={false} style={{ padding: 16 }}>
        {PLAN_BENEFITS_PRO.map((b, i) => {
          const Icon = Ico[b.icon] || Ico.check;
          return (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '9px 0',
              borderBottom: i === PLAN_BENEFITS_PRO.length - 1 ? 'none' : `0.5px solid ${theme.line}`,
            }}>
              <div style={{
                width: 28, height: 28, borderRadius: 8,
                background: `${accent}18`, color: accent,
                display:'flex', alignItems:'center', justifyContent:'center',
                flexShrink: 0,
              }}><Icon size={14}/></div>
              <span style={{ fontSize: 13, color: theme.text, lineHeight: 1.4 }}>{b.text}</span>
            </div>
          );
        })}
      </Card>
    </div>
  );
}

// ───── Shared payment method card (no auto-renewal toggle) ─────
function PaymentMethodCard({ theme, accent }) {
  const s = SUBSCRIPTION;
  return (
    <div style={{ padding: '22px 16px 0' }}>
      <SectionLabel theme={theme} style={{ padding: '0 4px 10px' }}>Payment method</SectionLabel>
      <Card theme={theme} padded={false}>
        <div style={{ display:'flex', alignItems:'center', gap: 12, padding: '14px 16px' }}>
          <div style={{
            width: 44, height: 30, borderRadius: 6,
            background: 'linear-gradient(135deg, #1a1f71, #2a3699)',
            color: '#fff', fontFamily: FONTS.mono, fontWeight: 700, fontSize: 10.5,
            display:'flex', alignItems:'center', justifyContent:'center',
            flexShrink: 0, letterSpacing: 0.5,
          }}>VISA</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, color: theme.text, fontWeight: 500 }}>{s.paymentMethod.brand} ending {s.paymentMethod.last4}</div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute, marginTop: 2, letterSpacing: 0.4 }}>Expires {s.paymentMethod.expiry}</div>
          </div>
          <button style={{ background:'transparent', border:'none', color: accent, fontSize: 12, fontWeight: 600, fontFamily: FONTS.ui, cursor:'pointer', padding: 0 }}>
            Update
          </button>
        </div>
      </Card>
    </div>
  );
}

// ───── Cancel button (no grayed text below) ─────
function CancelButton({ theme, onCancel }) {
  return (
    <div style={{ padding: '24px 16px 0' }}>
      <button onClick={onCancel} style={{
        width: '100%',
        background: theme.surface,
        border: `0.5px solid ${theme.line2}`,
        borderRadius: 16,
        padding: '14px',
        color: theme.negative,
        fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
        cursor: 'pointer',
      }}>Cancel subscription</button>
    </div>
  );
}

Object.assign(window, { SubscriptionScreen });
