// ============================================================
// SOCIAL PROOF TOAST — random "X tocmai a cumpărat..." notification
// ------------------------------------------------------------
// - Appears on all pages every 5-10 minutes (randomized)
// - Real Romanian names + cities + real account sizes
// - Mentions affiliate codes (Apex: NWAPJXME, Tradeify: TYRONE)
// - Subtle pop sound (Web Audio API, no mp3 hosted)
// - Click → navigate to firm's detail page
// - Mobile-friendly position (bottom-left desktop, bottom-center mobile)
// ============================================================

const SP_FIRMS = {
  apex: {
    name: 'Apex Trader Funding',
    short: 'Apex',
    logo: 'assets/logo-apex-fit.png',
    code: 'NWAPJXME',
    color: '#5AC8FF', // cyan/blue (acid blue accent)
    accentRgb: '90, 200, 255',
    page: 'propfirms/apex',
    accounts: ['25K', '50K', '75K', '100K', '150K', '250K', '300K'],
  },
  tradeify: {
    name: 'Tradeify',
    short: 'Tradeify',
    logo: 'assets/logo-tradeify-icon.png',
    code: 'TYRONE',
    color: '#FFCB52', // gold
    accentRgb: '255, 203, 82',
    page: 'propfirms/tradeify',
    accounts: ['25K', '50K', '100K', '150K'],
  },
  fundednext: {
    name: 'FundedNext Futures',
    short: 'FundedNext',
    logo: 'assets/logo-fundednext-fit.png',
    code: null,
    color: '#B7FF1A', // acid green
    accentRgb: '183, 255, 26',
    page: 'propfirms/fundednext',
    accounts: ['50K', '100K', '200K'],
  },
};

// Romanian first names + last initial — ~95% male, ~5% female
// (target audience is mostly male NASDAQ futures traders)
const SP_NAMES = [
  // Male (38)
  'Andrei P.', 'Cristian D.', 'Alexandru M.', 'Bogdan I.', 'Răzvan G.',
  'Mihai R.', 'Adrian V.', 'Sorin B.', 'Vlad H.', 'Ștefan A.',
  'Cosmin E.', 'Florin Z.', 'Dragoș U.', 'Marius Q.', 'Octavian R.',
  'George N.', 'Paul T.', 'Cătălin M.', 'Tudor V.', 'Eduard L.',
  'Daniel F.', 'Liviu S.', 'Cezar T.', 'Robert D.', 'Iulian C.',
  'Sebastian P.', 'Lucian K.', 'Darius G.', 'Mircea N.', 'Gabriel R.',
  'Horia B.', 'Dorin M.', 'Ionuț V.', 'Alin P.', 'Claudiu R.',
  'Emanuel S.', 'Toma B.', 'Bogdan-Ioan O.',
  // Female (2)
  'Maria S.', 'Andreea J.',
];

// (Cities removed by request — show only first name + initial.)

// Subtle "doorbell" notification sound using Web Audio API
const spPlayPop = () => {
  try {
    const Ctx = window.AudioContext || window.webkitAudioContext;
    if (!Ctx) return;
    const ctx = new Ctx();
    const now = ctx.currentTime;

    // Two-tone ding (high → low)
    const tones = [
      { freq: 988, start: 0,    dur: 0.18, vol: 0.10 },  // B5
      { freq: 660, start: 0.10, dur: 0.30, vol: 0.08 },  // E5
    ];

    tones.forEach((t) => {
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.type = 'sine';
      osc.frequency.setValueAtTime(t.freq, now + t.start);
      gain.gain.setValueAtTime(0.0001, now + t.start);
      gain.gain.exponentialRampToValueAtTime(t.vol, now + t.start + 0.02);
      gain.gain.exponentialRampToValueAtTime(0.0001, now + t.start + t.dur);
      osc.connect(gain);
      gain.connect(ctx.destination);
      osc.start(now + t.start);
      osc.stop(now + t.start + t.dur + 0.05);
    });

    // Auto-close audio context after sound finishes
    setTimeout(() => { try { ctx.close(); } catch (_) {} }, 700);
  } catch (e) {
    // Browser blocked autoplay — silent fail
  }
};

const spPickRandomSale = () => {
  const firmKeys = Object.keys(SP_FIRMS);
  const firmKey = firmKeys[Math.floor(Math.random() * firmKeys.length)];
  const firm = SP_FIRMS[firmKey];
  const account = firm.accounts[Math.floor(Math.random() * firm.accounts.length)];
  const name = SP_NAMES[Math.floor(Math.random() * SP_NAMES.length)];
  const minutesAgo = 1 + Math.floor(Math.random() * 8); // 1-8 min ago
  return { firmKey, firm, account, name, minutesAgo, id: Date.now() + Math.random() };
};

const SocialProofToast = ({ onNav }) => {
  const [sale, setSale] = React.useState(null);
  const [closing, setClosing] = React.useState(false);
  const timersRef = React.useRef({ show: null, hide: null, schedule: null });

  const dismiss = React.useCallback(() => {
    setClosing(true);
    setTimeout(() => {
      setSale(null);
      setClosing(false);
    }, 350);
  }, []);

  const showOne = React.useCallback(() => {
    const newSale = spPickRandomSale();
    setSale(newSale);
    setClosing(false);
    spPlayPop();
    // Auto-hide after 25 seconds (user requested 20-30s window)
    clearTimeout(timersRef.current.hide);
    timersRef.current.hide = setTimeout(() => dismiss(), 25000);
  }, [dismiss]);

  React.useEffect(() => {
    // After the 2nd popup, switch to recurring random 5-10 min intervals
    const scheduleRecurring = () => {
      const delayMin = 5 + Math.random() * 5; // 5-10 min random
      const delayMs = delayMin * 60 * 1000;
      timersRef.current.schedule = setTimeout(() => {
        showOne();
        scheduleRecurring();
      }, delayMs);
    };

    // Schedule:
    //   1st popup  → 1 minute after page load
    //   2nd popup  → at minute 5 (4 min after the first one)
    //   3rd+ popup → 5-10 min random after the previous one
    timersRef.current.show = setTimeout(() => {
      showOne();
      // 2nd popup at minute 5 = 4 minutes after the 1st one
      timersRef.current.second = setTimeout(() => {
        showOne();
        scheduleRecurring();
      }, 4 * 60 * 1000);
    }, 1 * 60 * 1000);

    return () => {
      clearTimeout(timersRef.current.show);
      clearTimeout(timersRef.current.second);
      clearTimeout(timersRef.current.hide);
      clearTimeout(timersRef.current.schedule);
    };
  }, [showOne]);

  if (!sale) return null;

  // Card click navigates to firm page but does NOT dismiss
  // (only X button or auto-timer dismisses)
  const handleCardClick = () => {
    if (onNav && sale.firm.page) {
      onNav(sale.firm.page);
    }
  };

  return (
    <div className={`sp-toast ${closing ? 'sp-closing' : 'sp-opening'}`}>
      <div
        className="sp-card"
        onClick={handleCardClick}
        style={{
          '--accent': sale.firm.color,
          '--accent-rgb': sale.firm.accentRgb,
        }}>
        <button
          className="sp-close"
          onClick={(e) => { e.stopPropagation(); dismiss(); }}
          aria-label="Close">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>

        <div className="sp-logo-wrap">
          <img src={sale.firm.logo} alt={sale.firm.short} className="sp-logo" />
        </div>

        <div className="sp-body">
          <div className="sp-eyebrow">
            <span className="sp-pulse" />
            PROMOȚIE ACTIVATĂ
          </div>
          <div className="sp-title">
            <strong>{sale.name}</strong> <span className="sp-muted">a cumpărat</span>
          </div>
          <div className="sp-detail">
            Cont <strong className="sp-amount">${sale.account}</strong> {sale.firm.short}
            {sale.firm.code && (
              <> · cu codul <span className="sp-code">{sale.firm.code}</span></>
            )}
          </div>
          <div className="sp-foot">
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
            </svg>
            acum {sale.minutesAgo} {sale.minutesAgo === 1 ? 'minut' : 'minute'}
          </div>
        </div>
      </div>

      <style>{`
        .sp-toast {
          position: fixed;
          left: 20px;
          bottom: 24px;
          z-index: 95;
          width: min(360px, calc(100vw - 40px));
          cursor: pointer;
          user-select: none;
          pointer-events: auto;
        }
        .sp-opening { animation: sp-slide-in 0.5s cubic-bezier(0.22, 1, 0.36, 1); }
        .sp-closing { animation: sp-slide-out 0.35s cubic-bezier(0.55, 0, 0.78, 0.32) forwards; }

        @keyframes sp-slide-in {
          from { opacity: 0; transform: translateX(-30px) translateY(10px); }
          to   { opacity: 1; transform: translateX(0) translateY(0); }
        }
        @keyframes sp-slide-out {
          from { opacity: 1; transform: translateX(0); }
          to   { opacity: 0; transform: translateX(-30px); }
        }

        .sp-card {
          position: relative;
          display: grid;
          grid-template-columns: 52px 1fr;
          gap: 14px;
          padding: 14px 38px 14px 14px;
          border-radius: 16px;
          background:
            linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.01) 100%),
            rgba(10, 10, 12, 0.85);
          backdrop-filter: blur(20px) saturate(140%);
          -webkit-backdrop-filter: blur(20px) saturate(140%);
          border: 1px solid rgba(var(--accent-rgb), 0.28);
          box-shadow:
            0 20px 50px rgba(0,0,0,0.55),
            0 0 30px rgba(var(--accent-rgb), 0.12),
            inset 0 1px 0 rgba(255,255,255,0.05);
          transition: transform 0.25s ease, box-shadow 0.25s ease, border-color 0.25s ease;
        }
        .sp-card:hover {
          transform: translateY(-2px);
          border-color: rgba(var(--accent-rgb), 0.45);
          box-shadow:
            0 24px 60px rgba(0,0,0,0.65),
            0 0 40px rgba(var(--accent-rgb), 0.20),
            inset 0 1px 0 rgba(255,255,255,0.08);
        }

        .sp-close {
          position: absolute;
          top: 8px; right: 8px;
          width: 22px; height: 22px;
          padding: 0;
          border-radius: 6px;
          background: rgba(255,255,255,0.04);
          border: 1px solid rgba(255,255,255,0.08);
          color: rgba(255,255,255,0.4);
          cursor: pointer;
          display: grid; place-items: center;
          transition: background 0.2s, color 0.2s, border-color 0.2s;
        }
        .sp-close:hover {
          background: rgba(255,255,255,0.10);
          color: #fff;
          border-color: rgba(255,255,255,0.18);
        }

        .sp-logo-wrap {
          width: 52px; height: 52px;
          border-radius: 12px;
          background:
            radial-gradient(circle at 30% 20%, rgba(var(--accent-rgb), 0.18) 0%, transparent 70%),
            rgba(0,0,0,0.55);
          border: 1px solid rgba(var(--accent-rgb), 0.30);
          display: grid; place-items: center;
          overflow: hidden;
          box-shadow: inset 0 1px 0 rgba(255,255,255,0.06);
        }
        .sp-logo {
          width: 38px; height: 38px;
          object-fit: contain;
          display: block;
        }

        .sp-body { min-width: 0; }
        .sp-eyebrow {
          display: inline-flex; align-items: center; gap: 6px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 9.5px;
          letter-spacing: 0.16em;
          text-transform: uppercase;
          color: var(--accent);
          margin-bottom: 4px;
        }
        .sp-pulse {
          width: 6px; height: 6px;
          border-radius: 50%;
          background: var(--accent);
          box-shadow: 0 0 8px var(--accent);
          animation: sp-pulse 1.6s ease-in-out infinite;
        }
        @keyframes sp-pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50%      { opacity: 0.5; transform: scale(0.85); }
        }
        .sp-title {
          font-size: 13.5px;
          line-height: 1.35;
          color: rgba(255,255,255,0.92);
          margin-bottom: 4px;
        }
        .sp-title strong { font-weight: 600; }
        .sp-muted { color: rgba(255,255,255,0.50); font-weight: 400; }
        .sp-detail {
          font-size: 12px;
          line-height: 1.45;
          color: rgba(255,255,255,0.72);
        }
        .sp-amount {
          color: var(--accent);
          font-weight: 700;
          letter-spacing: -0.01em;
        }
        .sp-code {
          display: inline-block;
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          padding: 1px 6px;
          margin-left: 2px;
          border-radius: 4px;
          background: rgba(var(--accent-rgb), 0.12);
          color: var(--accent);
          border: 1px solid rgba(var(--accent-rgb), 0.25);
          letter-spacing: 0.04em;
        }
        .sp-foot {
          margin-top: 6px;
          display: inline-flex; align-items: center; gap: 5px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 10px;
          color: rgba(255,255,255,0.42);
        }
        .sp-foot svg { color: rgba(255,255,255,0.42); }

        @media (max-width: 600px) {
          .sp-toast {
            left: 12px;
            right: 12px;
            bottom: 14px;
            width: auto;
          }
          .sp-card { grid-template-columns: 44px 1fr; gap: 12px; padding: 12px 36px 12px 12px; }
          .sp-logo-wrap { width: 44px; height: 44px; }
          .sp-logo { width: 32px; height: 32px; }
          .sp-title { font-size: 12.5px; }
          .sp-detail { font-size: 11.5px; }
        }

        @media (prefers-reduced-motion: reduce) {
          .sp-opening, .sp-closing { animation: none; }
          .sp-pulse { animation: none; }
        }
      `}</style>
    </div>
  );
};

Object.assign(window, { SocialProofToast });
