// ============================================================
// MARKETING PROMPT MODAL
// ------------------------------------------------------------
// Apare DUPĂ login pentru userii care nu au acceptat marketing-ul
// la creearea contului. Folosește același stil ca AuthModal (.amx-*).
//
// Logic:
//  - Mounted in app.jsx
//  - Triggered when: user logs in AND marketing_consent === false
//    AND sessionStorage doesn't have "tyrone_mkt_asked" set
//  - "Da, vreau"  → update profile.marketing_consent + call brevo-sync
//  - "Nu mulțumesc" → set session flag so we don't ask again this session
// ============================================================

const MarketingPromptModal = ({ user, onClose }) => {
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') handleNo(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // "Nu mulțumesc" → just close. Popup will appear again next time the
  // user signs in (until they actually accept marketing).
  const handleNo = () => onClose();

  const handleYes = async () => {
    if (!window.sb || !user?.id) { onClose(); return; }
    setBusy(true);
    setErr('');
    try {
      // 1) Persist consent on the profile (user can write this column directly;
      //    only marketing_status / brevo_contact_id / synced_at / tags are blocked
      //    by the trigger — those are set by the edge function via service role).
      const { error: updErr } = await window.sb
        .from('profiles')
        .update({
          marketing_consent: true,
          marketing_consent_at: new Date().toISOString(),
        })
        .eq('id', user.id);
      if (updErr) throw updErr;

      // 2) Sync with Brevo (creates the contact + tags + flips marketing_status='active')
      const { error: fnErr } = await window.sb.functions.invoke('brevo-sync', {
        body: {
          action: 'subscribe',
          source: 'login',
          tags: [
            'Free Member',
            'Marketing Accepted',
            'Not Elite',
            'Late Opt-in',
          ],
        },
      });
      if (fnErr) {
        // Don't block UX if Brevo is down — consent already saved
        console.warn('[brevo-sync] failed after late opt-in:', fnErr);
      }

      onClose();
    } catch (e) {
      setErr(e.message || 'A apărut o eroare. Încearcă din nou.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="amx-overlay" onClick={handleNo}>
      <div className="amx-atmos">
        <div className="amx-gradient" />
        <div className="amx-blob amx-blob-top" />
        <div className="amx-blob amx-blob-bot" />
      </div>

      <button className="amx-close" onClick={handleNo} aria-label="Close"><Icon name="x" size={18}/></button>

      <div className="amx-card-wrap" onClick={(e) => e.stopPropagation()}>
        <div className="amx-beams">
          <span className="amx-beam amx-beam-top" />
          <span className="amx-beam amx-beam-right" />
          <span className="amx-beam amx-beam-bottom" />
          <span className="amx-beam amx-beam-left" />
          <span className="amx-dot amx-dot-tl" />
          <span className="amx-dot amx-dot-tr" />
          <span className="amx-dot amx-dot-br" />
          <span className="amx-dot amx-dot-bl" />
        </div>

        <div className="amx-card">
          <div className="amx-grid-pattern" />

          <div className="amx-head">
            <div className="amx-eyebrow"><span className="dot" />OFERTE & MATERIALE</div>
            <h1 className="amx-title">Vrei să primești ofertele?</h1>
            <p className="amx-sub">
              <span className="amx-highlight">Reduceri mari</span> la prop firms, <span className="amx-highlight">materiale gratuite</span>, update-uri Apex/Tradeify/FundedNext și oferte pentru <span className="amx-highlight">Elite Plan</span>.
            </p>
          </div>

          {err && <div className="amx-error" style={{ marginBottom: 12 }}>{err}</div>}

          <div className="mkt-actions">
            <button
              type="button"
              className="amx-btn-primary mkt-yes"
              onClick={handleYes}
              disabled={busy}>
              {busy ? <span className="amx-spinner" /> : <>DA, VREAU <span className="amx-arrow">→</span></>}
            </button>
            <button
              type="button"
              className="mkt-no"
              onClick={handleNo}
              disabled={busy}>
              Nu, mulțumesc
            </button>
          </div>

          <p className="amx-bottom amx-bottom-sm" style={{ marginTop: 14 }}>
            Poți schimba oricând preferința. Zero spam — 1-2 emailuri pe săptămână maxim.
          </p>
        </div>
      </div>

      <style>{`
        .mkt-actions {
          display: flex;
          flex-direction: column;
          gap: 10px;
          margin-top: 6px;
        }
        .mkt-yes { width: 100%; }
        .mkt-no {
          width: 100%;
          height: 42px;
          border-radius: 10px;
          background: rgba(255,255,255,0.04);
          color: rgba(255,255,255,0.72);
          border: 1px solid rgba(255,255,255,0.10);
          font: inherit;
          font-size: 13px;
          font-weight: 500;
          cursor: pointer;
          transition: background 0.2s, color 0.2s, border-color 0.2s;
        }
        .mkt-no:hover:not(:disabled) {
          background: rgba(255,255,255,0.07);
          color: #fff;
          border-color: rgba(255,255,255,0.18);
        }
        .mkt-no:disabled { opacity: 0.5; cursor: not-allowed; }
      `}</style>
    </div>
  );
};

Object.assign(window, { MarketingPromptModal });
