// Cancel subscription — 2-step retention flow (exit survey → tailored offer → confirm)

const CANCEL_REASONS = [
  { id: 'price',    glyph: '%',  label: "It's too expensive" },
  { id: 'usage',    glyph: '↓',  label: "I don't use it enough" },
  { id: 'features', glyph: '!',  label: 'Missing features / technical issues' },
  { id: 'other',    glyph: '?',  label: "Other / I just don't need it" },
];

// (planTier × reason) → tailored offer; null = graceful exit, no offer step.
// Monthly: every reason gets 50% off 2 months. "features" also collects feedback.
// Annual: no offers — go straight to cancellation.
const HALF_OFF = {
  cta: 'Claim 50% off 2 months', tag: '50% off 2 months',
};

const OFFER_MATRIX = {
  monthly: {
    price:    { ...HALF_OFF,
                headline: 'Times are tough — 50% off your next 2 months.',
                body: 'Stay on Pro and we’ll cut your next two bills in half.' },
    usage:    { ...HALF_OFF,
                headline: 'Take it slower at half price.',
                body: 'Get 50% off your next 2 months — no rush to use it all at once.' },
    features: { ...HALF_OFF,
                headline: 'Tell us what we miss — we’ll build it.',
                body: 'Send us a quick note about what’s missing. While we build it, your next 2 months are 50% off.',
                feedback: true },
    other:    { ...HALF_OFF,
                headline: 'Before you go — 50% off your next 2 months.',
                body: 'Stay with Pro at half price for two months and see if it clicks.' },
  },
  annual: {
    price:    null,
    usage:    null,
    features: null,
    other:    null,
  },
};

function SubscriptionCancelScreen({ theme, accent, planTier = 'annual', onClose, onCancelled }) {
  const [step, setStep] = React.useState('survey'); // 'survey' | 'offer' | 'confirmed' | 'cancelled'
  const [reason, setReason] = React.useState(null);
  const [feedback, setFeedback] = React.useState('');

  const offer = reason ? OFFER_MATRIX[planTier][reason] : null;

  const pickReason = (r) => {
    setReason(r);
    if (OFFER_MATRIX[planTier][r]) setStep('offer');
    else setStep('cancelled'); // graceful exit
  };

  if (step === 'confirmed' || step === 'cancelled') {
    const isAccepted = step === 'confirmed';
    return (
      <Screen theme={theme} padTop={0} padBottom={40}>
        <NavBar theme={theme} title={isAccepted ? 'Offer applied' : 'Subscription cancelled'} onBack={onClose}/>
        <div style={{ padding: '40px 16px 0', textAlign: 'center' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 32, margin: '0 auto 18px',
            background: isAccepted ? `${theme.positive}18` : `${theme.textMute}18`,
            color: isAccepted ? theme.positive : theme.textDim,
            display:'flex', alignItems:'center', justifyContent:'center',
          }}><Ico.check size={28} sw={2.4}/></div>
          <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text }}>
            {isAccepted ? 'You’re all set' : 'We’re sorry to see you go'}
          </div>
          <div style={{ fontSize: 13, color: theme.textDim, marginTop: 8, padding: '0 24px', lineHeight: 1.55 }}>
            {isAccepted
              ? `${offer.tag} applied to your account. You’ll see it on your next invoice.`
              : 'Your subscription will end at the close of your current billing period. Pro features stay on until then.'}
          </div>
          <button onClick={() => { onClose(); if (!isAccepted) onCancelled && onCancelled(); }} style={{
            marginTop: 28, background: theme.text, color: theme.bg,
            border: 'none', borderRadius: 16,
            padding: '14px 28px',
            fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
            cursor: 'pointer',
          }}>Done</button>
        </div>
      </Screen>
    );
  }

  if (step === 'offer' && offer) {
    return (
      <Screen theme={theme} padTop={0} padBottom={40}>
        <NavBar theme={theme} title="One last thing" onBack={() => setStep('survey')}/>

        <div style={{ padding: '8px 16px 0', textAlign: 'center' }}>
          <div style={{
            display: 'inline-block',
            fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1.4, textTransform: 'uppercase',
            color: accent, padding: '5px 10px',
            background: `${accent}14`, borderRadius: 999,
            marginBottom: 14,
          }}>Special offer · {offer.tag}</div>
          <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, lineHeight: 1.3, padding: '0 8px' }}>
            {offer.headline}
          </div>
          <div style={{ fontSize: 13, color: theme.textDim, marginTop: 10, padding: '0 16px', lineHeight: 1.55 }}>
            {offer.body}
          </div>
        </div>

        {offer.feedback && (
          <div style={{ padding: '20px 16px 0' }}>
            <SectionLabel theme={theme} style={{ padding: '0 4px 8px' }}>What’s missing?</SectionLabel>
            <textarea
              value={feedback}
              onChange={(e) => setFeedback(e.target.value)}
              placeholder="A feature, an integration, anything…"
              rows={4}
              style={{
                width: '100%', boxSizing: 'border-box',
                background: theme.surface,
                border: `0.5px solid ${theme.line2}`,
                borderRadius: 14,
                padding: '12px 14px',
                color: theme.text, fontFamily: FONTS.ui, fontSize: 13,
                resize: 'none', outline: 'none',
              }}/>
          </div>
        )}

        <div style={{ padding: '20px 16px 0' }}>
          <Card theme={theme} padded={false} style={{
            padding: 22,
            background: `linear-gradient(155deg, ${accent}14, ${theme.surface} 90%)`,
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: FONTS.display, fontSize: 30, color: theme.text, letterSpacing: -0.5 }}>{offer.tag}</div>
              <div style={{ fontFamily: FONTS.mono, fontSize: 10, letterSpacing: 1, textTransform: 'uppercase', color: theme.textMute, marginTop: 6 }}>
                applied automatically
              </div>
            </div>
          </Card>
        </div>

        <div style={{ padding: '24px 16px 0' }}>
          <button onClick={() => setStep('confirmed')} style={{
            width: '100%',
            background: theme.text, color: theme.bg,
            border: 'none', borderRadius: 16,
            padding: '14px',
            fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
            cursor: 'pointer',
          }}>{offer.cta}</button>

          <button onClick={() => setStep('cancelled')} style={{
            marginTop: 12, width: '100%',
            background: 'transparent', border: 'none',
            color: theme.textDim,
            fontFamily: FONTS.ui, fontSize: 12.5, fontWeight: 500,
            cursor: 'pointer', padding: '10px 0',
            textDecoration: 'underline', textUnderlineOffset: 3,
          }}>No thanks, just cancel my subscription</button>
        </div>
      </Screen>
    );
  }

  // Step 1 — exit survey
  return (
    <Screen theme={theme} padTop={0} padBottom={40}>
      <NavBar theme={theme} title="Cancel subscription" onBack={onClose}/>

      <div style={{ padding: '8px 16px 0', textAlign: 'center' }}>
        <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, lineHeight: 1.3 }}>
          We’re sorry to see you go.
        </div>
        <div style={{ fontSize: 13, color: theme.textDim, marginTop: 10, padding: '0 16px', lineHeight: 1.55 }}>
          Could you tell us why you’re cancelling today? It helps us improve.
        </div>
      </div>

      <div style={{ padding: '24px 16px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {CANCEL_REASONS.map(r => (
          <button key={r.id} onClick={() => pickReason(r.id)} style={{
            width: '100%', textAlign: 'left',
            display: 'flex', alignItems: 'center', gap: 12,
            background: theme.surface,
            border: `0.5px solid ${theme.line2}`, borderRadius: 16,
            padding: '16px 16px',
            color: theme.text, cursor: 'pointer',
          }}>
            <div style={{
              width: 34, height: 34, borderRadius: 10,
              background: theme.surface2, color: theme.textDim,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: FONTS.display, fontSize: 16, flexShrink: 0,
            }}>{r.glyph}</div>
            <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500 }}>{r.label}</span>
            <Ico.chevR size={14} stroke={theme.textMute}/>
          </button>
        ))}
      </div>

      <div style={{ padding: '20px 16px 0' }}>
        <button onClick={onClose} style={{
          width: '100%',
          background: 'transparent', border: 'none',
          color: theme.textDim,
          fontFamily: FONTS.ui, fontSize: 12.5, fontWeight: 500,
          cursor: 'pointer', padding: '10px 0',
        }}>Never mind, keep my subscription</button>
      </div>
    </Screen>
  );
}

Object.assign(window, { SubscriptionCancelScreen });
