// SubscriptionScreen.jsx — AegisComply Subscription Plans (updated pricing)

const subStyles = {
  page: { padding: 24 },
  hero: { textAlign: 'center', marginBottom: 28 },
  heroTitle: { fontFamily: "'Helvetica',sans-serif", fontSize: 26, fontWeight: 800, color: '#0F172A', marginBottom: 8, letterSpacing: '-0.02em' },
  heroSub: { fontSize: 14, color: '#64748B', maxWidth: 500, margin: '0 auto' },
  toggleRow: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12, marginBottom: 28 },
  toggleLabel: { fontSize: 13, fontWeight: 500, color: '#64748B' },
  toggleWrap: { width: 48, height: 26, borderRadius: 13, cursor: 'pointer', position: 'relative', display: 'flex', alignItems: 'center', padding: '0 3px', transition: 'background 200ms' },
  toggleKnob: { width: 20, height: 20, borderRadius: '50%', background: 'white', boxShadow: '0 1px 3px rgba(0,0,0,0.15)', transition: 'transform 200ms' },
  saveBadge: { background: '#F0FDF4', color: '#16A34A', border: '1px solid #BBF7D0', fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 10 },
  // Pilot banner
  pilotBanner: { background: 'linear-gradient(135deg,#0B1F3A 0%,#1A3558 100%)', borderRadius: 10, padding: '18px 24px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 16 },
  pilotIcon: { width: 48, height: 48, borderRadius: 10, background: 'rgba(13,148,136,0.25)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
  pilotText: { fontSize: 15, fontWeight: 700, color: 'white' },
  pilotSub: { fontSize: 12, color: 'rgba(255,255,255,0.55)', marginTop: 3, lineHeight: 1.5 },
  pilotBtn: { marginLeft: 'auto', height: 38, padding: '0 20px', border: 'none', borderRadius: 7, background: '#0D9488', fontSize: 13, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", whiteSpace: 'nowrap', flexShrink: 0 },
  // Plans
  plansGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 28 },
  planCard: { background: 'white', border: '2px solid #E2E8F0', borderRadius: 12, padding: '24px 22px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)', position: 'relative', transition: 'box-shadow 200ms' },
  planCardFeatured: { border: '2px solid #0D9488', boxShadow: '0 8px 28px rgba(13,148,136,0.15)' },
  featuredBadge: { position: 'absolute', top: -13, left: '50%', transform: 'translateX(-50%)', background: '#0D9488', color: 'white', fontSize: 11, fontWeight: 700, padding: '3px 16px', borderRadius: 10, letterSpacing: '0.06em', whiteSpace: 'nowrap' },
  planName: { fontFamily: "'Helvetica',sans-serif", fontSize: 19, fontWeight: 800, color: '#0F172A', marginBottom: 4 },
  planDesc: { fontSize: 12, color: '#64748B', marginBottom: 16, lineHeight: 1.5 },
  planPrice: { fontFamily: "'Helvetica',sans-serif", fontSize: 38, fontWeight: 800, color: '#0F172A', lineHeight: 1, marginBottom: 2 },
  planPriceUnit: { fontSize: 16, fontWeight: 400, color: '#94A3B8' },
  planPriceSub: { fontSize: 12, color: '#94A3B8', marginBottom: 8 },
  planSaving: { fontSize: 12, fontWeight: 600, color: '#16A34A', background: '#F0FDF4', padding: '3px 10px', borderRadius: 5, display: 'inline-block', marginBottom: 16 },
  planBtn: { width: '100%', height: 42, borderRadius: 7, fontSize: 14, fontWeight: 700, cursor: 'pointer', border: 'none', fontFamily: "'DM Sans',sans-serif", marginBottom: 20, transition: 'all 150ms' },
  planBtnPrimary: { background: '#0D9488', color: 'white' },
  planBtnOutline: { background: 'white', color: '#0B1F3A', border: '2px solid #0B1F3A' },
  featureList: { listStyle: 'none', padding: 0, margin: 0 },
  featureItem: { display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 9, fontSize: 13 },
  featureCheck: { flexShrink: 0, marginTop: 1 },
  divider: { height: 1, background: '#F1F5F9', margin: '16px 0' },
  // Payment
  paymentCard: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 12, padding: '22px 26px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)', marginBottom: 20 },
  paymentTitle: { fontFamily: "'Helvetica',sans-serif", fontSize: 15, fontWeight: 700, color: '#0F172A', marginBottom: 4 },
  paymentSub: { fontSize: 13, color: '#64748B', marginBottom: 18 },
  bankGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },
  bankDetail: { background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 7, padding: '12px 14px' },
  bankLabel: { fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 4 },
  bankValue: { fontSize: 14, fontWeight: 600, color: '#0F172A', fontFamily: "'JetBrains Mono',monospace" },
  bankValueNormal: { fontSize: 14, fontWeight: 600, color: '#0F172A', fontFamily: "'DM Sans',sans-serif" },
  paymentNote: { background: '#F0FDFA', border: '1px solid #99F6E4', borderRadius: 8, padding: '12px 14px', fontSize: 12, color: '#0F766E', marginTop: 14, lineHeight: 1.6 },
  // FAQ
  faqCard: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 12, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' },
  faqRow: { padding: '14px 20px', borderBottom: '1px solid #F1F5F9', cursor: 'pointer' },
  faqQ: { fontSize: 13, fontWeight: 600, color: '#0F172A', display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  faqA: { fontSize: 13, color: '#475569', marginTop: 8, lineHeight: 1.6 },
};

const PLANS_MONTHLY = [
  {
    name: 'Full Access — Monthly',
    desc: 'Complete industrial compliance platform. All modules included, no limits.',
    price: 289, unit: '/mo', billing: 'Billed monthly. Cancel anytime.',
    saving: null, featured: true, btnStyle: 'primary',
    features: [
      { text: 'Unlimited equipment records', ok: true },
      { text: 'Calibration tracking, history & QR', ok: true },
      { text: 'PPE inventory, analytics & QR issuance', ok: true },
      { text: 'ROI Report (PDF export)', ok: true },
      { text: 'Auto-quotation (calibration & PPE)', ok: true },
      { text: 'Document management (50 GB)', ok: true },
      { text: 'Up to 10 user accounts', ok: true },
      { text: 'Priority email & chat support', ok: true },
      { text: 'API access & webhooks', ok: false },
      { text: 'Dedicated account manager', ok: false },
    ],
  },
  {
    name: 'Full Access — Yearly',
    desc: 'Same complete access, billed annually. Save RM 480 vs monthly.',
    price: 249, unit: '/mo', billing: 'RM 2,988 billed annually (save RM 480/yr)',
    saving: 'Save 14% vs monthly', featured: false, btnStyle: 'outline',
    features: [
      { text: 'Unlimited equipment records', ok: true },
      { text: 'Calibration tracking, history & QR', ok: true },
      { text: 'PPE inventory, analytics & QR issuance', ok: true },
      { text: 'ROI Report (PDF export)', ok: true },
      { text: 'Auto-quotation (calibration & PPE)', ok: true },
      { text: 'Document management (50 GB)', ok: true },
      { text: 'Up to 10 user accounts', ok: true },
      { text: 'Priority email & chat support', ok: true },
      { text: 'API access & webhooks', ok: false },
      { text: 'Dedicated account manager', ok: false },
    ],
  },
];

const faqs = [
  { q: 'What is included in the 14-day pilot?', a: 'Full access to all features — no restrictions, no credit card required. Your pilot starts the moment you register. After 14 days, you choose a plan to continue.' },
  { q: 'How do I pay?', a: 'Transfer directly to our company bank account (details below). Once payment is confirmed, your account continues without interruption. Send your receipt to billing@aegiscomply.my.' },
  { q: 'What is the difference between monthly and yearly billing?', a: 'Both plans offer identical features. Yearly billing costs RM 249/mo (billed RM 2,988 at once), saving you RM 480 compared to monthly billing at RM 289/mo.' },
  { q: 'Can I upgrade or cancel?', a: 'Cancel anytime — no penalty. For cancellations, your account remains active until the end of your paid period. Data is retained for 90 days after cancellation.' },
  { q: 'Do you offer invoices for company accounts?', a: 'Yes — official tax invoices (with SSM registration number) are issued for all payments. Send your company details to billing@aegiscomply.my.' },
  { q: 'What happens to my data?', a: 'All your equipment, calibration, and PPE records can be exported as CSV or PDF at any time. Data is retained for 90 days after account closure.' },
];

function CheckIcon({ ok }) {
  return ok ? (
    <svg style={subStyles.featureCheck} width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
  ) : (
    <svg style={{ ...subStyles.featureCheck, opacity: 0.25 }} width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#94A3B8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
  );
}

function SubscriptionScreen({ user }) {
  const [openFaq, setOpenFaq] = React.useState(null);
  const [selected, setSelected] = React.useState(null);

  // Derive subscription status from user
  const tier        = user?.tier || 'pilot';
  const isFull      = tier === 'full_forever';
  const isFrozen    = tier === 'frozen';
  const isPilot     = tier === 'pilot';
  const isActive    = tier === 'monthly' || tier === 'yearly';
  const subEnd      = user?.subscription_end ? new Date(user.subscription_end) : null;
  const pilotStart  = user?.pilot_start ? new Date(user.pilot_start) : null;
  const today       = new Date();

  // Calculate days remaining
  let daysRemaining = null;
  let statusText    = '';
  let statusSub     = '';
  let statusBg      = 'linear-gradient(135deg,#0B1F3A 0%,#1A3558 100%)';
  let statusIconBg  = 'rgba(13,148,136,0.25)';
  let statusIconColor = '#14B8A6';

  if (isFull) {
    statusText = 'Full Access Forever';
    statusSub  = 'You have permanent unrestricted access. No subscription required.';
    statusBg   = 'linear-gradient(135deg,#0B1F3A 0%,#0D9488 100%)';
  } else if (isFrozen) {
    statusText = 'Subscription Lapsed — Read-Only Mode';
    statusSub  = 'Your account is in read-only mode. Renew below to restore full access.';
    statusBg   = 'linear-gradient(135deg,#7F1D1D 0%,#DC2626 100%)';
    statusIconBg = 'rgba(255,255,255,0.2)';
    statusIconColor = 'white';
  } else if (isActive && subEnd) {
    daysRemaining = Math.ceil((subEnd - today) / 86400000);
    statusText = `${tier === 'yearly' ? 'Yearly' : 'Monthly'} Subscription Active`;
    statusSub  = daysRemaining > 30
      ? `Active until ${subEnd.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })} (${daysRemaining} days remaining).`
      : `Renews in ${daysRemaining} days. Transfer payment below to extend.`;
    statusBg   = 'linear-gradient(135deg,#0B1F3A 0%,#16A34A 100%)';
  } else if (isPilot && pilotStart) {
    const pilotEnd = new Date(pilotStart.getTime() + 14 * 86400000);
    daysRemaining = Math.max(0, Math.ceil((pilotEnd - today) / 86400000));
    statusText = `14-Day Pilot · ${daysRemaining} days remaining`;
    statusSub  = daysRemaining > 0
      ? `Pilot ends ${pilotEnd.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}. Subscribe below to continue after.`
      : 'Pilot has ended. Subscribe below to restore full access.';
    if (daysRemaining <= 3) statusBg = 'linear-gradient(135deg,#92400E 0%,#D97706 100%)';
  }

  return (
    <div style={subStyles.page}>
      {/* Hero */}
      <div style={subStyles.hero}>
        <div style={subStyles.heroTitle}>{isFull ? 'Your Subscription' : 'Simple, transparent pricing'}</div>
        <div style={subStyles.heroSub}>{isFull ? 'Permanent full access — no subscription required.' : 'One plan. Full access. Start with a free 14-day pilot — no credit card needed.'}</div>
      </div>

      {/* Personalized status banner */}
      <div style={{ ...subStyles.pilotBanner, background: statusBg }}>
        <div style={{ ...subStyles.pilotIcon, background: statusIconBg }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={statusIconColor} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            {isFull ? (
              <><polyline points="20 6 9 17 4 12"/></>
            ) : isFrozen ? (
              <><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></>
            ) : (
              <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
            )}
          </svg>
        </div>
        <div>
          <div style={subStyles.pilotText}>{statusText}</div>
          <div style={subStyles.pilotSub}>{statusSub}</div>
        </div>
        {!isFull && (
          <button
            style={subStyles.pilotBtn}
            onClick={() => document.getElementById('payment-section')?.scrollIntoView({ behavior: 'smooth' })}
          >
            {isFrozen || (isPilot && daysRemaining <= 0) ? 'Renew Now →' : 'View Plans →'}
          </button>
        )}
      </div>

      {/* Plans */}
      <div style={subStyles.plansGrid}>
        {PLANS_MONTHLY.map((p, i) => (
          <div key={i} style={{ ...subStyles.planCard, ...(p.featured ? subStyles.planCardFeatured : {}), ...(selected === i ? { boxShadow: '0 0 0 3px rgba(13,148,136,0.3)' } : {}) }}>
            {p.featured && <div style={subStyles.featuredBadge}>RECOMMENDED</div>}
            <div style={subStyles.planName}>{p.name}</div>
            <div style={subStyles.planDesc}>{p.desc}</div>
            <div style={subStyles.planPrice}>RM {p.price}<span style={subStyles.planPriceUnit}>{p.unit}</span></div>
            <div style={subStyles.planPriceSub}>{p.billing}</div>
            {p.saving && <div style={subStyles.planSaving}>{p.saving}</div>}
            <button
              style={{ ...subStyles.planBtn, ...(p.btnStyle === 'primary' ? subStyles.planBtnPrimary : subStyles.planBtnOutline), marginTop: p.saving ? 8 : 16 }}
              onClick={() => setSelected(i)}
            >
              {selected === i ? '✓ Selected — See Payment Details' : `Choose ${i === 0 ? 'Monthly' : 'Yearly'}`}
            </button>
            <ul style={subStyles.featureList}>
              {p.features.map((f, j) => (
                <li key={j} style={{ ...subStyles.featureItem, color: f.ok ? '#334155' : '#CBD5E1' }}>
                  <CheckIcon ok={f.ok}/>{f.text}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>

      {/* Payment details */}
      <div id="payment-section" style={subStyles.paymentCard}>
        <div style={subStyles.paymentTitle}>
          Payment Details
          {selected !== null && <span style={{ marginLeft: 10, fontSize: 12, fontWeight: 600, background: '#F0FDFA', color: '#0D9488', padding: '2px 10px', borderRadius: 6 }}>{PLANS_MONTHLY[selected].name}</span>}
        </div>
        <div style={subStyles.paymentSub}>Bank transfer directly to our company account. No credit card or online payment gateway required.</div>
        <div style={subStyles.bankGrid}>
          <div style={subStyles.bankDetail}><div style={subStyles.bankLabel}>Company Name</div><div style={subStyles.bankValueNormal}>AegisComply Sdn Bhd</div></div>
          <div style={subStyles.bankDetail}><div style={subStyles.bankLabel}>Bank</div><div style={subStyles.bankValueNormal}>Maybank (Malayan Banking Berhad)</div></div>
          <div style={subStyles.bankDetail}><div style={subStyles.bankLabel}>Account Number</div><div style={subStyles.bankValue}>5621 4892 3301</div></div>
          <div style={subStyles.bankDetail}><div style={subStyles.bankLabel}>Account Type</div><div style={subStyles.bankValueNormal}>Business Current Account</div></div>
          <div style={subStyles.bankDetail}><div style={subStyles.bankLabel}>Amount</div><div style={subStyles.bankValue}>{selected !== null ? (selected === 0 ? 'RM 289.00/mo' : 'RM 2,988.00/yr') : 'Select plan above'}</div></div>
          <div style={subStyles.bankDetail}><div style={subStyles.bankLabel}>Reference</div><div style={subStyles.bankValue}>{selected !== null ? `AEGIS-${selected === 0 ? 'MO' : 'YR'}-${new Date().getFullYear()}` : 'Select plan above'}</div></div>
        </div>
        <div style={subStyles.paymentNote}>
          After payment, email your receipt to <strong>billing@aegiscomply.my</strong> with your company name, registered email, and selected plan. Activation within 1 business day. WhatsApp: <strong>+60 12-345 6789</strong>
        </div>
      </div>

      {/* FAQ */}
      <div style={{ fontFamily: "'Helvetica',sans-serif", fontSize: 15, fontWeight: 700, color: '#0F172A', marginBottom: 14 }}>Frequently Asked Questions</div>
      <div style={subStyles.faqCard}>
        {faqs.map((f, i) => (
          <div key={i} style={{ ...subStyles.faqRow, borderBottom: i === faqs.length - 1 ? 'none' : '1px solid #F1F5F9' }} onClick={() => setOpenFaq(openFaq === i ? null : i)}>
            <div style={subStyles.faqQ}>
              {f.q}
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94A3B8" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ transform: openFaq === i ? 'rotate(180deg)' : 'none', transition: 'transform 150ms', flexShrink: 0 }}><polyline points="6 9 12 15 18 9"/></svg>
            </div>
            {openFaq === i && <div style={subStyles.faqA}>{f.a}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { SubscriptionScreen });
