// screen-settings.jsx — Settings: Plan, Billing, Account, Team
// Exports: SettingsScreen

const SettingsScreen = ({ persona, tweaks }) => {
  const [tab, setTab] = React.useState('plan');
  const [upgradeOpen, setUpgradeOpen] = React.useState(false);
  const [cancelOpen, setCancelOpen] = React.useState(false);
  const { dark } = tweaks;

  const cardBg = dark ? 'rgba(255,255,255,0.06)' : 'var(--white)';
  const cardBorder = dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)';
  const textColor = dark ? 'rgba(245,241,232,0.9)' : 'var(--fg-1)';
  const subColor = dark ? 'rgba(245,241,232,0.5)' : 'var(--fg-3)';

  const PLANS = [
    { id: 'starter', name: 'Starter', price: '$100', features: ['Limited push campaigns', 'Core screens + editor', 'Judge.me', 'Email support', 'A/B testing (2 variants)'] },
    { id: 'growth', name: 'Growth', price: '$200', features: ['Higher push limits', 'All screens + editor', '5 integrations', 'Priority email', '5 A/Z variants', '3 team members'], current: persona.id === 'nour' },
    { id: 'pro', name: 'Pro', price: '$300', features: ['Unlimited push', 'All integrations', 'Unlimited A/Z testing', 'Priority chat', 'Unlimited team', 'Custom components'], current: persona.id === 'marcus' },
  ];

  const usage = persona.id === 'nour'
    ? [{ label: 'Push notifications', used: 840, limit: 2000 }, { label: 'In-app campaigns', used: 3, limit: 10 }, { label: 'Team members', used: 1, limit: 3 }]
    : [{ label: 'Push notifications', used: 6609, limit: null }, { label: 'In-app campaigns', used: 18, limit: null }, { label: 'Team members', used: 4, limit: null }];

  const PlanTab = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      {/* Current plan */}
      <div style={{ background: 'var(--ink)', borderRadius: 14, padding: 28, color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 20 }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.5)', fontWeight: 500, marginBottom: 6 }}>Current plan</div>
          <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 36, color: 'var(--honey)', lineHeight: 1 }}>{persona.plan}</div>
          <div style={{ fontSize: 13, color: 'rgba(245,241,232,0.65)', marginTop: 8 }}>
            {persona.id === 'nour'
              ? `Free trial — ${persona.trialDays} days remaining. Billed at $200/mo after trial.`
              : 'Active subscription — $300/mo, billed monthly via Stripe.'}
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'flex-end' }}>
          {persona.id === 'nour' && (
            <div style={{ background: 'rgba(232,184,58,0.15)', border: '1px solid rgba(232,184,58,0.3)', borderRadius: 8, padding: '10px 16px', textAlign: 'right' }}>
              <div style={{ fontSize: 12, color: 'var(--honey)', fontWeight: 500 }}>{persona.trialDays} days left in trial</div>
              <div style={{ fontSize: 11, color: 'rgba(245,241,232,0.5)', marginTop: 2 }}>Paymob · •••• 4819</div>
            </div>
          )}
          <window.Button variant="secondary" size="sm" onClick={() => setCancelOpen(true)} style={{ color: 'rgba(245,241,232,0.6)', borderColor: 'rgba(245,241,232,0.2)' }}>Manage subscription →</window.Button>
        </div>
      </div>

      {/* Usage meters */}
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: textColor, marginBottom: 16 }}>Usage this month</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {usage.map(u => {
            const pct = u.limit ? Math.round((u.used / u.limit) * 100) : null;
            return (
              <div key={u.label}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13 }}>
                  <span style={{ color: textColor, fontWeight: 500 }}>{u.label}</span>
                  <span style={{ fontFamily: 'var(--font-mono)', color: pct && pct >= 80 ? 'var(--amber)' : textColor }}>
                    {u.used.toLocaleString()}{u.limit ? ` / ${u.limit.toLocaleString()}` : ' — unlimited'}
                  </span>
                </div>
                {u.limit ? <window.ProgressBar value={u.used} max={u.limit} /> : (
                  <div style={{ height: 6, borderRadius: 999, background: 'var(--mint-tint)' }}><div style={{ height: '100%', width: '100%', background: 'var(--mint)', borderRadius: 999, opacity: 0.5 }}></div></div>
                )}
                {pct && pct >= 80 && <div style={{ fontSize: 11, color: 'var(--amber)', marginTop: 5 }}>⚠ {100 - pct}% remaining — consider upgrading.</div>}
              </div>
            );
          })}
        </div>
      </div>

      {/* Plan comparison */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        {PLANS.map(plan => (
          <div key={plan.id} style={{ background: plan.current ? 'var(--ink)' : cardBg, border: `2px solid ${plan.current ? 'var(--ink)' : cardBorder}`, borderRadius: 12, padding: 20, color: plan.current ? 'var(--paper)' : textColor, position: 'relative' }}>
            {plan.current && <div style={{ position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)', background: 'var(--honey)', color: 'var(--ink)', fontSize: 10, fontWeight: 600, padding: '3px 10px', borderRadius: 999, whiteSpace: 'nowrap' }}>Current plan</div>}
            <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', opacity: plan.current ? 0.6 : 0.5, fontWeight: 500, marginBottom: 8 }}>{plan.name}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 30, lineHeight: 1, marginBottom: 12, color: plan.current ? 'var(--honey)' : textColor }}>{plan.price}<span style={{ fontSize: 12, opacity: 0.5 }}>/mo</span></div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {plan.features.map(f => (
                <div key={f} style={{ display: 'flex', gap: 7, fontSize: 11, alignItems: 'flex-start' }}>
                  <i data-lucide="check" style={{ width: 12, height: 12, flexShrink: 0, marginTop: 2, color: plan.current ? 'var(--honey)' : 'var(--mint)' }}></i>
                  <span style={{ opacity: 0.85 }}>{f}</span>
                </div>
              ))}
            </div>
            {!plan.current && (
              <window.Button size="sm" variant={plan.id === 'pro' ? 'primary' : 'secondary'} onClick={() => setUpgradeOpen(true)} style={{ marginTop: 14, width: '100%', justifyContent: 'center' }}>
                {plan.id === 'starter' ? 'Downgrade' : 'Upgrade →'}
              </window.Button>
            )}
          </div>
        ))}
      </div>
    </div>
  );

  const BillingTab = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 600 }}>
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: textColor, marginBottom: 16 }}>Payment method</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
          <div style={{ width: 46, height: 32, background: persona.id === 'nour' ? '#1A6B44' : '#635BFF', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <span style={{ fontSize: 9, fontWeight: 700, color: '#fff', letterSpacing: '0.05em' }}>{persona.id === 'nour' ? 'PAYMOB' : 'STRIPE'}</span>
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: textColor }}>{persona.id === 'nour' ? 'Banque Misr Visa' : 'Visa ending in 4242'}</div>
            <div style={{ fontSize: 12, color: subColor }}>•••• {persona.id === 'nour' ? '4819' : '4242'} · Expires 12/27</div>
          </div>
          <window.Button variant="ghost" size="sm" style={{ marginLeft: 'auto' }}>Update →</window.Button>
        </div>
        <div style={{ fontSize: 12, color: subColor, paddingTop: 14, borderTop: `1px solid ${cardBorder}` }}>
          Payment processor: <strong style={{ color: textColor }}>{persona.id === 'nour' ? 'Paymob (MENA)' : 'Stripe (Global)'}</strong> · Auto-selected based on your store region. <span style={{ color: 'var(--fg-link)', cursor: 'pointer', textDecoration: 'underline' }}>Switch gateway →</span>
        </div>
      </div>
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: textColor, marginBottom: 16 }}>Billing history</div>
        {persona.id === 'nour' ? (
          <div style={{ fontSize: 13, color: subColor }}>No charges yet — your trial ends in {persona.trialDays} days. You'll be billed $200 on June 28, 2026.</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <tbody>
              {[['Jun 1, 2026', 'Pro plan — June', '$300', 'Paid'], ['May 1, 2026', 'Pro plan — May', '$300', 'Paid'], ['Apr 1, 2026', 'Pro plan — April', '$300', 'Paid']].map(([date, desc, amt, status], i) => (
                <tr key={i} style={{ borderBottom: i < 2 ? `1px solid ${cardBorder}` : 'none' }}>
                  <td style={{ padding: '10px 0', color: subColor, fontSize: 12 }}>{date}</td>
                  <td style={{ padding: '10px 8px', color: textColor }}>{desc}</td>
                  <td style={{ padding: '10px 8px', fontFamily: 'var(--font-mono)', color: textColor }}>{amt}</td>
                  <td style={{ padding: '10px 0', textAlign: 'right' }}><window.StatusPill status="active" /></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );

  const AccountTab = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 560 }}>
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24, display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>Profile</div>
        <window.Input label="Full name" value={persona.id === 'nour' ? 'Nour Ahmed' : 'Marcus Thompson'} />
        <window.Input label="Email" value={persona.id === 'nour' ? 'nour@nourcairo.com' : 'marcus@marcuselectronics.com'} />
        <window.Input label="Shopify store URL" prefix="https://" value={persona.domain} />
        <window.Select label="Dashboard language" value="English" options={['English', 'Arabic (coming soon)']} />
        <window.Button size="sm">Save changes</window.Button>
      </div>
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24, display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>Notifications</div>
        {[['Trial expiring reminders', true], ['Push campaign performance', true], ['App store review status', true], ['Shopify sync alerts', false]].map(([label, checked]) => (
          <div key={label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 13, color: textColor }}>{label}</span>
            <window.Toggle checked={checked} onChange={() => {}} />
          </div>
        ))}
      </div>
    </div>
  );

  const tabs = [{ id: 'plan', label: 'Plan & usage' }, { id: 'billing', label: 'Billing' }, { id: 'account', label: 'Account' }, { id: 'team', label: 'Team' }];
  const screenContent = { plan: <PlanTab />, billing: <BillingTab />, account: <AccountTab />, team: (
    <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24, maxWidth: 560 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: textColor, marginBottom: 4 }}>Team members</div>
      <div style={{ fontSize: 12, color: subColor, marginBottom: 20 }}>Multi-user collaboration is available on Growth and Pro plans.</div>
      <window.EmptyState icon="users" title="Invite your team" description="Team collaboration UI launches in Phase 2. The database schema is ready — role-based access control for Owner, Designer, Marketing, and Viewer." action={<window.Button size="sm" variant="secondary">Get notified when ready →</window.Button>} />
    </div>
  )};

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1000 }}>
      <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, color: textColor, margin: 0 }}>Settings</h1>
      <window.Tabs tabs={tabs} active={tab} onSelect={setTab} />
      {screenContent[tab]}

      {upgradeOpen && (
        <window.Modal open onClose={() => setUpgradeOpen(false)} title="Upgrade plan" width={460}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: 0 }}>You're upgrading from <strong>Growth</strong> to <strong>Pro</strong>. A prorated charge of <strong>$150</strong> will be applied today for the remaining billing period.</p>
            <div style={{ background: 'var(--sand-50)', borderRadius: 8, padding: '14px 16px', fontSize: 13, color: 'var(--fg-2)' }}>
              Upgrade takes effect immediately. Your plan renews at $300/mo on July 1, 2026.
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <window.Button variant="secondary" onClick={() => setUpgradeOpen(false)}>Cancel</window.Button>
              <window.Button onClick={() => setUpgradeOpen(false)}>Confirm upgrade →</window.Button>
            </div>
          </div>
        </window.Modal>
      )}
    </div>
  );
};

window.SettingsScreen = SettingsScreen;
