// Telas: Histórico, Favoritos, Configurações, Paywall, Checkout, Compartilhamento
const { useState: useStateMisc, useEffect: useEffectMisc } = React;

function ListScreen({ t, lang, kind, items, onOpen, emptyText }) {
  if (!items.length) {
    return (
      <div className="mv-empty">
        <div className="mv-empty-mark">{kind === 'fav' ? '♡' : '◷'}</div>
        <p>{emptyText}</p>
      </div>
    );
  }
  return (
    <div className="mv-list">
      {items.map((it) => {
        const theme = window.THEMES.find(x => x.id === it.theme_id);
        const date = new Date(it.created_at || it.viewed_at);
        return (
          <button className="mv-list-row" key={it.id} onClick={() => onOpen(it)}>
            <div className="mv-list-icon">{theme?.icon || '✧'}</div>
            <div className="mv-list-meta">
              <div className="mv-list-ref">{it.verse_ref}</div>
              <div className="mv-list-theme">{theme ? theme[lang] : ''} · {date.toLocaleDateString(lang === 'pt' ? 'pt-BR' : lang === 'es' ? 'es-ES' : 'en-US')}</div>
            </div>
            <div className="mv-list-arr">›</div>
          </button>
        );
      })}
    </div>
  );
}

function Settings({ t, lang, setLang, profile, onSignOut, onUpgrade, trialDaysLeft, onEnableNotifications }) {
  const [notifStatus, setNotifStatus] = useStateMisc(
    'Notification' in window ? Notification.permission : 'unsupported'
  );

  async function handleEnableNotifications() {
    if (notifStatus === 'granted') return;
    const result = await Notification.requestPermission();
    setNotifStatus(result);
    if (result === 'granted' && onEnableNotifications) {
      onEnableNotifications();
    }
  }

  const notifLabels = {
    granted: { en: '🔔 Notifications enabled', pt: '🔔 Notificações ativadas', es: '🔔 Notificaciones activadas' },
    denied:  { en: '🔕 Blocked — enable in browser settings', pt: '🔕 Bloqueado — ative nas configurações do navegador', es: '🔕 Bloqueado — activa en configuración del navegador' },
    default: { en: '🔔 Enable daily verse notifications', pt: '🔔 Ativar notificações do versículo diário', es: '🔔 Activar notificaciones del versículo diario' },
  };
  const notifLabel = (notifLabels[notifStatus] || notifLabels.default)[lang] || (notifLabels[notifStatus] || notifLabels.default).en;
  return (
    <div className="mv-settings">
      <div className="mv-settings-header">
        <div className="mv-avatar">{(profile?.name || profile?.email || '?')[0].toUpperCase()}</div>
        <div>
          <div className="mv-set-name">{profile?.name || profile?.email?.split('@')[0] || '—'}</div>
          <div className="mv-set-email">{profile?.email || ''}</div>
        </div>
      </div>

      <div className="mv-set-section">
        <div className="mv-set-label">{t.plan}</div>
        <div className={'mv-plan-card ' + (profile?.subscription_status === 'active' ? 'is-active' : 'is-trial')}>
          {profile?.subscription_status === 'active' ? (
            <>
              <div className="mv-plan-status">{t.sub_active}</div>
              <div className="mv-plan-detail">{t.sub_until} {profile?.subscription_until ? new Date(profile.subscription_until).toLocaleDateString() : '—'}</div>
            </>
          ) : (
            <>
              <div className="mv-plan-status">{t.trial_active}</div>
              <div className="mv-plan-detail">{trialDaysLeft} {t.trial_left}</div>
              <button className="mv-btn-primary" style={{ marginTop: 12 }} onClick={onUpgrade}>{t.upgrade}</button>
            </>
          )}
        </div>
      </div>

      <div className="mv-set-section">
        <div className="mv-set-label">{t.language}</div>
        <LangSwitch lang={lang} setLang={setLang} />
      </div>

      {notifStatus !== 'unsupported' && 'Notification' in window && (
        <div className="mv-set-section">
          <button className="mv-set-row" onClick={handleEnableNotifications}
            disabled={notifStatus === 'granted' || notifStatus === 'denied'}
            style={{ opacity: notifStatus === 'denied' ? 0.5 : 1 }}>
            <span>{notifLabel}</span>
            {notifStatus === 'granted' && <span style={{ color: 'var(--gold)' }}>✓</span>}
            {notifStatus === 'default' && <span className="mv-list-arr">›</span>}
          </button>
        </div>
      )}

      <div className="mv-set-section">
        <button className="mv-set-row" onClick={onSignOut}>
          <span>{t.signout}</span>
          <span className="mv-list-arr">›</span>
        </button>
      </div>
    </div>
  );
}

function PlanPicker({ t, plan, onChange }) {
  return (
    <div className="mv-plan-grid">
      <button type="button" className={'mv-plan-opt' + (plan === 'monthly' ? ' is-on' : '')} onClick={() => onChange('monthly')}>
        <div className="mv-plan-opt-name">{t.plan_monthly}</div>
        <div className="mv-plan-opt-price">{t.plan_monthly_price}<span>{t.plan_per_month}</span></div>
        <div className="mv-plan-opt-equiv">&nbsp;</div>
      </button>
      <button type="button" className={'mv-plan-opt' + (plan === 'yearly' ? ' is-on' : '')} onClick={() => onChange('yearly')}>
        <span className="mv-plan-badge">{t.plan_best}</span>
        <div className="mv-plan-opt-name">{t.plan_yearly}</div>
        <div className="mv-plan-opt-price">{t.plan_yearly_price}<span>{t.plan_per_year}</span></div>
        <div className="mv-plan-opt-equiv">{t.plan_yearly_equiv}</div>
      </button>
    </div>
  );
}

function Paywall({ t, onSubscribe, onClose, plan, setPlan }) {
  return (
    <div className="mv-paywall-scr">
      <button className="mv-back mv-back-light" onClick={onClose} aria-label="close">×</button>
      <div className="mv-paywall-mark">✦</div>
      <h2 className="mv-h2">{t.paywall_title}</h2>
      <p className="mv-lead">{t.paywall_sub}</p>
      <PlanPicker t={t} plan={plan} onChange={setPlan} />
      <ul className="mv-paywall-list">
        {t.paywall_features.map((f, i) => <li key={i}><span className="mv-tick">✓</span>{f}</li>)}
      </ul>
      <button className="mv-btn-primary mv-btn-lg" style={{ width: '100%' }} onClick={() => onSubscribe(plan)}>
        {plan === 'monthly' ? `${t.choose_plan} — ${t.plan_monthly_price}${t.plan_per_month}` : `${t.choose_plan} — ${t.plan_yearly_price}${t.plan_per_year}`}
      </button>
    </div>
  );
}

function Checkout({ t, onClose, onConfirm, plan = 'yearly', setPlan }) {
  const [card, setCard] = useStateMisc('');
  const [exp, setExp] = useStateMisc('');
  const [cvc, setCvc] = useStateMisc('');
  const [done, setDone] = useStateMisc(false);
  const [loading, setLoading] = useStateMisc(false);

  const isMonthly = plan === 'monthly';
  const planLabel = isMonthly ? t.checkout_plan_monthly : t.checkout_plan_yearly;
  const priceLabel = isMonthly ? `${t.plan_monthly_price}${t.plan_per_month}` : `${t.plan_yearly_price}${t.plan_per_year}`;
  const totalLabel = isMonthly ? `${t.plan_monthly_price}.00` : `${t.plan_yearly_price}.00`;

  function fmt(v) { return v.replace(/\D/g, '').slice(0, 16).replace(/(.{4})/g, '$1 ').trim(); }
  function fmtExp(v) { v = v.replace(/\D/g, '').slice(0, 4); return v.length > 2 ? v.slice(0, 2) + '/' + v.slice(2) : v; }

  async function submit(e) {
    e.preventDefault();
    setLoading(true);
    await new Promise(r => setTimeout(r, 1100));
    setDone(true);
    setLoading(false);
    if (onConfirm && !done) {
      // surface the chosen plan up via onConfirm only on success-cta below
    }
  }

  if (done) {
    return (
      <div className="mv-checkout">
        <div className="mv-success">
          <div className="mv-success-mark">✦</div>
          <h2 className="mv-h2">{t.success_title}</h2>
          <p className="mv-lead">{t.success_sub}</p>
          <button className="mv-btn-primary mv-btn-lg" style={{ width: '100%', marginTop: 24 }} onClick={() => onConfirm(plan)}>{t.success_cta}</button>
        </div>
      </div>
    );
  }

  return (
    <div className="mv-checkout">
      <button className="mv-back" onClick={onClose} aria-label="close">←</button>
      <h2 className="mv-h2">{t.checkout_title}</h2>
      {setPlan && <PlanPicker t={t} plan={plan} onChange={setPlan} />}
      <div className="mv-order-card">
        <div>
          <div className="mv-order-plan">{planLabel}</div>
          <div className="mv-order-trial">{t.pricing_trial}</div>
        </div>
        <div className="mv-order-price">{priceLabel}</div>
      </div>
      <form onSubmit={submit} className="mv-form">
        <label className="mv-field">
          <span>{t.checkout_card}</span>
          <input value={card} onChange={e => setCard(fmt(e.target.value))} placeholder="4242 4242 4242 4242" inputMode="numeric" required />
        </label>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <label className="mv-field">
            <span>{t.checkout_exp}</span>
            <input value={exp} onChange={e => setExp(fmtExp(e.target.value))} placeholder="MM/YY" inputMode="numeric" required />
          </label>
          <label className="mv-field">
            <span>{t.checkout_cvc}</span>
            <input value={cvc} onChange={e => setCvc(e.target.value.replace(/\D/g, '').slice(0, 4))} placeholder="123" inputMode="numeric" required />
          </label>
        </div>
        <div className="mv-order-total">
          <span>{t.checkout_total}</span><span>${totalLabel.replace('$','')}</span>
        </div>
        <button className="mv-btn-primary mv-btn-lg" type="submit" disabled={loading} style={{ width: '100%' }}>
          {loading ? '…' : t.checkout_pay}
        </button>
        <p className="mv-fineprint" style={{ textAlign: 'center', marginTop: 8 }}>🔒 {t.checkout_secure}</p>
      </form>
    </div>
  );
}

function Share({ t, lang, payload, onClose }) {
  const [copied, setCopied] = useStateMisc(false);
  if (!payload) return null;

  const shareUrl = 'https://mywisdomverse.online';
  const callToAction = {
    en: '✨ Get your daily Bible verse — free for 7 days',
    pt: '✨ Receba seu versículo diário — 7 dias grátis',
    es: '✨ Recibe tu versículo diario — 7 días gratis',
  }[lang] || '✨ Get your daily Bible verse — free for 7 days';

  // Gera o canvas e retorna como Blob
  function generateImageBlob() {
    return new Promise((resolve) => {
      const c = document.createElement('canvas');
      c.width = 1080; c.height = 1080;
      const ctx = c.getContext('2d');
      const g = ctx.createRadialGradient(540, 380, 100, 540, 540, 800);
      g.addColorStop(0, '#fbf3df'); g.addColorStop(0.6, '#f1e3c0'); g.addColorStop(1, '#d8bd86');
      ctx.fillStyle = g; ctx.fillRect(0, 0, 1080, 1080);
      ctx.strokeStyle = 'rgba(122,90,48,0.3)'; ctx.lineWidth = 2;
      ctx.strokeRect(60, 60, 960, 960);
      ctx.fillStyle = '#7a5a30'; ctx.font = '64px serif'; ctx.textAlign = 'center';
      ctx.fillText('✧', 540, 200);
      ctx.fillStyle = '#3a2c14';
      ctx.font = 'italic 44px "Cormorant Garamond", serif';
      const words = payload.text.split(' ');
      let line = '', y = 420;
      for (const w of words) {
        const test = line + w + ' ';
        if (ctx.measureText(test).width > 880 && line) {
          ctx.fillText(line.trim(), 540, y); y += 60; line = w + ' ';
        } else { line = test; }
      }
      if (line) ctx.fillText(line.trim(), 540, y);
      ctx.font = '500 26px "Inter", sans-serif';
      ctx.fillStyle = '#7a5a30';
      ctx.fillText(payload.ref.toUpperCase(), 540, y + 80);
      ctx.strokeStyle = 'rgba(122,90,48,0.35)'; ctx.lineWidth = 1;
      ctx.beginPath(); ctx.moveTo(200, y + 120); ctx.lineTo(880, y + 120); ctx.stroke();
      ctx.font = '500 20px "Inter", sans-serif';
      ctx.fillStyle = 'rgba(122,90,48,0.6)';
      ctx.fillText('My Verse', 540, y + 170);
      c.toBlob(resolve, 'image/png');
    });
  }

  // Compartilhamento nativo com imagem + link
  async function shareNative() {
    const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);

    if (isMobile && navigator.share) {
      // Mobile: tenta share com imagem
      try {
        const blob = await generateImageBlob();
        const file = new File([blob], 'myverse.png', { type: 'image/png' });
        const shareData = {
          title: 'My Verse',
          text: callToAction,
          url: shareUrl,
        };
        if (navigator.canShare && navigator.canShare({ files: [file] })) {
          await navigator.share({ ...shareData, files: [file] });
        } else {
          await navigator.share(shareData);
        }
      } catch (e) {
        if (e.name !== 'AbortError') {
          // Fallback: copia texto
          navigator.clipboard.writeText(`"${payload.text}" — ${payload.ref}\n\n${callToAction}\n${shareUrl}`).catch(() => {});
          setCopied(true);
          setTimeout(() => setCopied(false), 1600);
        }
      }
    } else {
      // Desktop: copia link para área de transferência
      navigator.clipboard.writeText(`"${payload.text}" — ${payload.ref}\n\n${callToAction}\n${shareUrl}`).catch(() => {});
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    }
  }

  // WhatsApp direto (texto + link — sem duplicar)
  const whatsappText = `"${payload.text}" — ${payload.ref}\n\n${callToAction}\n${shareUrl}`;
  const whatsappUrl = `https://wa.me/?text=${encodeURIComponent(whatsappText)}`;

  // Download da imagem
  async function downloadImage() {
    const blob = await generateImageBlob();
    const a = document.createElement('a');
    a.download = `versiculo-${payload.ref.replace(/[^a-z0-9]/gi, '_')}.png`;
    a.href = URL.createObjectURL(blob); a.click();
    URL.revokeObjectURL(a.href);
  }

  return (
    <div className="mv-share-overlay" onClick={onClose} style={{ position:'fixed', inset:0, zIndex:9000, background:'rgba(20,16,8,0.6)', display:'flex', alignItems:'center', justifyContent:'center', padding:'20px' }}>
      <div className="mv-share-card" onClick={e => e.stopPropagation()} style={{ width:'100%', maxWidth:320, borderRadius:20, background:'var(--paper)', padding:'24px' }}>
        <div className="mv-share-preview">
          <div className="mv-share-mark">✧</div>
          <p className="mv-share-text">"{payload.text}"</p>
          <p className="mv-share-ref">{payload.ref}</p>
        </div>
        <h3 className="mv-share-title">{t.share_title}</h3>
        <div className="mv-share-actions">
          <button className="mv-share-btn mv-share-primary" onClick={shareNative}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
              <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
            </svg>
            {copied ? t.share_copied : (t.share_send || 'Share')}
          </button>
          <a className="mv-share-btn mv-share-whatsapp" href={whatsappUrl} target="_blank" rel="noopener noreferrer">
            <span>💬</span> WhatsApp
          </a>
          <button className="mv-share-btn" onClick={downloadImage}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
              <polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>
            </svg>
            {t.share_image}
          </button>
        </div>
        <button className="mv-share-close" onClick={onClose}>×</button>
      </div>
    </div>
  );
}

function FavDetail({ lang, item, onClose, onShare }) {
  if (!item) return null;
  const theme = window.THEMES?.find(x => x.id === item.theme_id);
  const themeName = theme?.[lang] || '';
  const shareLabel = { en: 'Share', pt: 'Compartilhar', es: 'Compartir' }[lang] || 'Share';

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 9000,
      background: 'rgba(30,20,8,0.6)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '24px 20px',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--paper)', borderRadius: 20, padding: '28px 24px',
        width: '100%', maxWidth: 320, position: 'relative',
        boxShadow: '0 8px 40px rgba(30,20,8,0.25)',
      }}>
        {/* Botão fechar */}
        <button onClick={onClose} style={{
          position: 'absolute', top: 12, right: 16,
          background: 'none', border: 'none', fontSize: 22,
          cursor: 'pointer', color: 'var(--ink-soft)', lineHeight: 1,
        }}>×</button>

        {/* Cartão do versículo */}
        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          {theme && <div style={{ fontSize: 24, marginBottom: 10 }}>{theme.icon}</div>}
          <p style={{
            fontFamily: 'var(--serif)', fontSize: 18, fontStyle: 'italic',
            color: 'var(--ink)', lineHeight: 1.65, marginBottom: 14,
          }}>"{item.text}"</p>
          <p style={{
            fontSize: 11, fontWeight: 700, letterSpacing: 2,
            color: 'var(--gold)', textTransform: 'uppercase',
          }}>{item.verse_ref}</p>
          {themeName && (
            <p style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 6, opacity: 0.6 }}>
              {themeName}
            </p>
          )}
        </div>

        {/* Divisor */}
        <div style={{ height: 1, background: 'var(--gold-soft)', margin: '0 0 16px' }} />

        {/* Botão compartilhar */}
        <button onClick={() => { onClose(); setTimeout(() => onShare(item), 100); }} style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          width: '100%', padding: '12px', borderRadius: 12,
          background: 'linear-gradient(135deg, var(--gold-deep), var(--gold))',
          border: 'none', color: '#fff', fontSize: 14, fontWeight: 700,
          cursor: 'pointer', fontFamily: 'var(--sans)',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
            <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>
            <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
          </svg>
          {shareLabel}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ListScreen, Settings, Paywall, Checkout, Share, FavDetail, PlanPicker });
