/* global React, window, firebase */
/* ============================================
   ReviewsMarquee — moving strip of customer
   comments for the featured EAs.
   • Two rows scroll in opposite directions, loop
     seamlessly, pause on hover.
   • Visitors can add their own comment (button
     below the wall) → saved to Firestore so it
     shows for everyone, plus localStorage so the
     author always sees it instantly.
   ============================================ */

const EFF_MARQUEE_REVIEWS = [
  // ── Sb Options Pro Ea ──────────────────────────────
  { name: 'Mohamed K.', loc: 'Prop Trader · UAE', stars: 5, ea: 'Sb Options Pro Ea', accent: 'cyan',
    text: 'Passed phase 1 of my $100k FTMO with Sb Options Pro in 12 days. The ATR stops keep drawdown sane on XAUUSD — exactly like the backtest.' },
  { name: 'James P.', loc: 'Retail · London', stars: 5, ea: 'Sb Options Pro Ea', accent: 'cyan',
    text: 'Been running it on EURUSD H1 for 3 months on IC Markets. Smooth equity curve, no crazy spikes. Set and forget honestly.' },
  { name: 'Bilal S.', loc: 'Swing Trader · Pakistan', stars: 4, ea: 'Sb Options Pro Ea', accent: 'cyan',
    text: 'Solid trend EA. Slower in ranging weeks but the news filter saved me twice already. Worth the license.' },
  { name: 'Andreas M.', loc: 'Retail · Germany', stars: 5, ea: 'Sb Options Pro Ea', accent: 'cyan',
    text: 'Verified the PF against my own MT5 logs and it matches. Rare to see a vendor publish every single trade.' },

  // ── Gold Master Pro EA ─────────────────────────────
  { name: 'Khaled A.', loc: 'Gold Trader · KSA', stars: 5, ea: 'Gold Master Pro EA', accent: 'amber',
    text: 'Gold Master Pro on XAUUSD is the only martingale I trust — the hard equity stop actually works. +14% last month on a $5k live account.' },
  { name: 'Wei L.', loc: 'Retail · Singapore', stars: 5, ea: 'Gold Master Pro EA', accent: 'amber',
    text: 'The news filter closes everything before NFP. That alone is worth it. Running it on a Pepperstone raw account.' },
  { name: 'Tomás R.', loc: 'Algo Dev · Spain', stars: 4, ea: 'Gold Master Pro EA', accent: 'amber',
    text: 'Aggressive but controlled. I lowered the lot multiplier and it sits at ~9% DD. Documentation is clear about the risk.' },
  { name: 'Fatima Z.', loc: 'Retail · Morocco', stars: 5, ea: 'Gold Master Pro EA', accent: 'amber',
    text: 'First EA that didn’t blow my account on gold. The equity stop gives me peace of mind overnight.' },

  // ── Blue Deer Ea ───────────────────────────────────
  { name: 'Daniel O.', loc: 'Prop Trader · Nigeria', stars: 5, ea: 'Blue Deer Ea', accent: 'green',
    text: 'The FVG / inversion logic on M5 is sharp. Blue Deer caught the London move three days straight. Cleanest entries I’ve seen.' },
  { name: 'Sara H.', loc: 'Retail · Egypt', stars: 5, ea: 'Blue Deer Ea', accent: 'green',
    text: 'Fractal model just makes sense once you watch it live. Took a small license first, upgraded after 2 weeks. No regrets.' },
  { name: 'Victor C.', loc: 'Day Trader · Brazil', stars: 4, ea: 'Blue Deer Ea', accent: 'green',
    text: 'Great on EURUSD and USDJPY. Needs a low-spread broker to shine — on my old broker the spread ate some trades.' },
  { name: 'Ahmad N.', loc: 'Retail · Jordan', stars: 5, ea: 'Blue Deer Ea', accent: 'green',
    text: 'Support answered my setup questions same day. EA was profitable from day one on a VPS. Very happy.' },

  // ── Blue Deer Ai EA ────────────────────────────────
  { name: 'Lina M.', loc: 'Quant · France', stars: 5, ea: 'Blue Deer Ai EA', accent: 'magenta',
    text: 'The AI layer adapts to volatility way better than the manual version. It sat out the choppy week and re-entered perfectly.' },
  { name: 'Omar F.', loc: 'Prop Trader · Qatar', stars: 5, ea: 'Blue Deer Ai EA', accent: 'magenta',
    text: 'Blue Deer Ai is doing the heavy lifting on my funded account. The model filters out the fakeouts the old EA used to take.' },
  { name: 'Ryan T.', loc: 'Retail · Canada', stars: 4, ea: 'Blue Deer Ai EA', accent: 'magenta',
    text: 'Smart EA. Fewer trades than I expected but the win rate is high. Quality over quantity, which I prefer.' },
  { name: 'Yusuf B.', loc: 'Retail · Turkey', stars: 5, ea: 'Blue Deer Ai EA', accent: 'magenta',
    text: 'Installed in minutes on my VPS. The AI confidence filter is genuinely different — best Gold EA I’ve run this year.' },
];

const MARQUEE_LS_KEY = 'eff_marquee_reviews_v1';
const MARQUEE_ACCENTS = ['cyan', 'magenta', 'green', 'amber'];

function loadLocalReviews() {
  try { return JSON.parse(localStorage.getItem(MARQUEE_LS_KEY) || '[]'); }
  catch { return []; }
}
function saveLocalReviews(list) {
  try { localStorage.setItem(MARQUEE_LS_KEY, JSON.stringify(list)); } catch (e) {}
}

function StarRow({ n }) {
  return (
    <div className="flex" style={{ gap: 1 }} aria-label={n + ' stars'}>
      {[1, 2, 3, 4, 5].map(i => (
        <svg key={i} width="12" height="12" viewBox="0 0 24 24" fill={i <= n ? 'var(--amber)' : 'none'} stroke="var(--amber)" strokeWidth="1.5">
          <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
        </svg>
      ))}
    </div>
  );
}

function ReviewChip({ r }) {
  const accent = r.accent || 'cyan';
  return (
    <div className="review-chip">
      <div className="flex gap-3" style={{ alignItems: 'center', marginBottom: 10 }}>
        <div className="review-avatar" style={{ background: `var(--${accent})` }}>{(r.name || '?')[0].toUpperCase()}</div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13.5, lineHeight: 1.1 }}>{r.name}</div>
          {r.loc && <div className="text-xs text-muted" style={{ marginTop: 2 }}>{r.loc}</div>}
        </div>
        <div style={{ flex: 1 }}/>
        <StarRow n={r.stars}/>
      </div>
      <p className="text-sm" style={{ lineHeight: 1.55, color: 'var(--text-2)' }}>{r.text}</p>
      <div className="flex gap-2 mt-3" style={{ alignItems: 'center', flexWrap: 'wrap' }}>
        {r.ea && <span className="review-ea-tag" style={{ color: `var(--${accent})`, borderColor: `color-mix(in oklch, var(--${accent}) 45%, transparent)` }}>{r.ea}</span>}
        <span className="flex gap-1" style={{ alignItems: 'center', fontSize: 10, color: 'var(--green)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--green)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
          VERIFIED
        </span>
      </div>
    </div>
  );
}

function MarqueeRow({ items, dir, speed }) {
  const doubled = [...items, ...items];
  return (
    <div className="marquee-row">
      <div className={`marquee-track ${dir === 'right' ? 'marquee-right' : 'marquee-left'}`}
        style={{ animationDuration: speed + 's' }}>
        {doubled.map((r, i) => <ReviewChip key={i} r={r}/>)}
      </div>
    </div>
  );
}

/* ── Add-comment modal ─────────────────────────────── */
function AddCommentModal({ onClose, onSubmit, eaOptions }) {
  const [name, setName] = React.useState('');
  const [loc, setLoc] = React.useState('');
  const [ea, setEa] = React.useState(eaOptions[0] || '');
  const [stars, setStars] = React.useState(5);
  const [text, setText] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  async function submit() {
    setErr('');
    if (!name.trim()) { setErr('Please enter your name.'); return; }
    if (text.trim().length < 12) { setErr('Please write a little more about your experience.'); return; }
    setBusy(true);
    try {
      await onSubmit({ name: name.trim(), loc: loc.trim(), ea, stars, text: text.trim() });
      onClose();
    } catch (e) {
      setErr(e.message || 'Could not submit. Please try again.');
      setBusy(false);
    }
  }

  return (
    <Modal onClose={onClose}>
      <div style={{ width: '100%', maxWidth: 520 }}>
        <div className="flex-between mb-4">
          <div>
            <span className="eyebrow">SHARE YOUR EXPERIENCE</span>
            <h2 className="mt-2" style={{ fontSize: 22 }}>Add your comment</h2>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm">×</button>
        </div>

        <div className="grid grid-2" style={{ gap: 12 }}>
          <div className="field">
            <label>Your name</label>
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Ahmed M." maxLength={40}/>
          </div>
          <div className="field">
            <label>Location / role (optional)</label>
            <input className="input" value={loc} onChange={e => setLoc(e.target.value)} placeholder="e.g. Retail · Egypt" maxLength={40}/>
          </div>
        </div>

        <div className="grid grid-2 mt-3" style={{ gap: 12 }}>
          <div className="field">
            <label>Which EA?</label>
            <select className="input" value={ea} onChange={e => setEa(e.target.value)}>
              {eaOptions.map(o => <option key={o} value={o}>{o}</option>)}
            </select>
          </div>
          <div className="field">
            <label>Rating</label>
            <div className="flex gap-1" style={{ alignItems: 'center', height: 44 }}>
              {[1, 2, 3, 4, 5].map(i => (
                <button key={i} type="button" onClick={() => setStars(i)} aria-label={i + ' stars'}
                  style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 2, lineHeight: 0 }}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill={i <= stars ? 'var(--amber)' : 'none'} stroke="var(--amber)" strokeWidth="1.5">
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                  </svg>
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="field mt-3">
          <label>Your comment</label>
          <textarea className="input" rows="4" value={text} onChange={e => setText(e.target.value)}
            placeholder="Share how the EA performed for you…" maxLength={320}/>
          <div className="text-xs text-muted mt-1" style={{ textAlign: 'right' }}>{text.length}/320</div>
        </div>

        {err && <div className="panel mt-2" style={{ padding: 10, background: 'rgba(255,59,92,0.08)', borderColor: 'rgba(255,59,92,0.3)' }}><span className="text-red font-mono text-xs">⚠ {err}</span></div>}

        <div className="flex gap-2 mt-4">
          <div style={{ flex: 1 }}/>
          <button className="btn btn-ghost" onClick={onClose} disabled={busy}>Cancel</button>
          <button className="btn btn-primary btn-sheen" onClick={submit} disabled={busy}>
            {busy ? <span className="typing"><span/><span/><span/></span> : 'Post comment'}
          </button>
        </div>
      </div>
    </Modal>
  );
}

/* ── Admin: manage which EA names appear in the dropdown ── */
function ManageDropdownModal({ onClose, allNames, hiddenSet }) {
  const [hidden, setHidden] = React.useState(() => new Set(hiddenSet));
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [ok, setOk] = React.useState(false);

  function toggle(name) {
    setHidden(prev => {
      const next = new Set(prev);
      if (next.has(name)) next.delete(name); else next.add(name);
      return next;
    });
  }
  function showAll() { setHidden(new Set()); }
  function hideAll() { setHidden(new Set(allNames)); }

  async function save() {
    setErr(''); setSaving(true); setOk(false);
    try {
      await window.EAReports.saveSiteConfig({ marqueeHidden: [...hidden] });
      setOk(true);
      setTimeout(onClose, 700);
    } catch (e) {
      setErr(e.message || 'Save failed');
      setSaving(false);
    }
  }

  const visibleCount = allNames.length - hidden.size;

  return (
    <Modal onClose={onClose}>
      <div style={{ width: '100%', maxWidth: 520 }}>
        <div className="flex-between mb-4">
          <div>
            <span className="eyebrow" style={{ color: 'var(--magenta)' }}>ADMIN · COMMENT DROPDOWN</span>
            <h2 className="mt-2" style={{ fontSize: 22 }}>Which EAs can customers pick?</h2>
            <p className="text-muted text-sm mt-2">Toggle each EA. Hidden ones won’t appear in the “Which EA?” list when a visitor adds a comment. {visibleCount} of {allNames.length} visible.</p>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm">×</button>
        </div>

        <div className="flex gap-2 mb-3">
          <button type="button" className="btn btn-ghost btn-sm" onClick={showAll}>Show all</button>
          <button type="button" className="btn btn-ghost btn-sm" onClick={hideAll}>Hide all</button>
        </div>

        <div style={{ maxHeight: '52vh', overflowY: 'auto', paddingRight: 6 }}>
          <div className="flex-col gap-2">
            {allNames.map(name => {
              const isVisible = !hidden.has(name);
              return (
                <div key={name} className="flex-between" style={{
                  padding: '10px 14px', borderRadius: 10,
                  border: '1px solid var(--line)',
                  background: isVisible ? 'rgba(0,255,148,0.04)' : 'rgba(255,255,255,0.02)',
                  opacity: isVisible ? 1 : 0.6,
                }}>
                  <span style={{ fontWeight: 600, fontSize: 14 }}>{name}</span>
                  <button type="button" onClick={() => toggle(name)}
                    className="btn btn-sm"
                    style={{
                      borderRadius: 6, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em',
                      border: `1px solid ${isVisible ? 'rgba(0,255,148,0.4)' : 'rgba(255,59,92,0.4)'}`,
                      background: isVisible ? 'rgba(0,255,148,0.08)' : 'rgba(255,59,92,0.08)',
                      color: isVisible ? 'var(--green)' : 'var(--red)',
                    }}>
                    {isVisible ? '👁 SHOWN' : '🚫 HIDDEN'}
                  </button>
                </div>
              );
            })}
            {allNames.length === 0 && <div className="text-muted text-sm">No EAs found.</div>}
          </div>
        </div>

        {err && <div className="panel mt-3" style={{ padding: 10, background: 'rgba(255,59,92,0.08)', borderColor: 'rgba(255,59,92,0.3)' }}><span className="text-red font-mono text-xs">⚠ {err}</span></div>}
        {ok && <div className="panel mt-3" style={{ padding: 10, background: 'rgba(0,255,148,0.08)', borderColor: 'rgba(0,255,148,0.3)' }}><span className="text-green font-mono text-xs">✓ Saved · changes are live</span></div>}

        <div className="flex gap-2 mt-4">
          <div style={{ flex: 1 }}/>
          <button className="btn btn-ghost" onClick={onClose} disabled={saving}>Cancel</button>
          <button className="btn btn-primary btn-sheen" onClick={save} disabled={saving}>
            {saving ? <span className="typing"><span/><span/><span/></span> : 'Save & publish'}
          </button>
        </div>
      </div>
    </Modal>
  );
}

function ReviewsMarquee() {
  const [localReviews, setLocalReviews] = React.useState(loadLocalReviews);
  const [fsReviews, setFsReviews] = React.useState([]);
  const [modalOpen, setModalOpen] = React.useState(false);
  const [manageOpen, setManageOpen] = React.useState(false);
  const [justPosted, setJustPosted] = React.useState(false);
  const [adminOn, setAdminOn] = React.useState(!!window.__effAdminMode);
  const [cfgTick, setCfgTick] = React.useState(0);

  // Re-render when admin toggles config (hidden dropdown EAs) or admin mode.
  React.useEffect(() => {
    const onCfg = () => setCfgTick(t => t + 1);
    const onAdmin = () => setAdminOn(!!window.__effAdminMode);
    window.addEventListener('eff_config_changed', onCfg);
    window.addEventListener('eff_eas_changed', onCfg);
    window.addEventListener('eff_admin_changed', onAdmin);
    return () => {
      window.removeEventListener('eff_config_changed', onCfg);
      window.removeEventListener('eff_eas_changed', onCfg);
      window.removeEventListener('eff_admin_changed', onAdmin);
    };
  }, []);

  // Full EA name list (current, admin-renamed names).
  const allEaNames = React.useMemo(() => {
    const names = (window.EAReports?.effectiveList?.() || window.EA_LIST || [])
      .map(e => e.name).filter(Boolean);
    return [...new Set(names)];
  }, [cfgTick]);

  // Admin-managed hidden set for the dropdown.
  const hiddenSet = React.useMemo(() => {
    const cfg = window.EAReports?.getSiteConfig?.() || {};
    return new Set(cfg.marqueeHidden || []);
  }, [cfgTick]);

  // Options shown to customers in the "Which EA?" dropdown.
  const eaOptions = React.useMemo(() => {
    const visible = allEaNames.filter(n => !hiddenSet.has(n));
    const fallback = ['Sb Options Pro Ea', 'Gold Master Pro EA', 'Blue Deer Ea', 'Blue Deer Ai EA'];
    return visible.length ? visible : fallback;
  }, [allEaNames, hiddenSet]);

  // Live subscription to public comments
  React.useEffect(() => {
    if (!window.fb) return;
    const unsub = window.fb.db.collection('marquee_reviews')
      .orderBy('createdAt', 'desc').limit(40)
      .onSnapshot(
        snap => {
          const rows = [];
          snap.forEach(doc => {
            const d = doc.data();
            rows.push({ id: doc.id, name: d.name, loc: d.loc, stars: d.stars, ea: d.ea, text: d.text, accent: d.accent });
          });
          setFsReviews(rows);
        },
        err => console.warn('marquee reviews sync:', err)
      );
    return () => unsub();
  }, []);

  async function handleSubmit(data) {
    const accent = MARQUEE_ACCENTS[Math.floor(Math.random() * MARQUEE_ACCENTS.length)];
    const review = { ...data, accent, ts: Date.now() };

    // Always store locally so the author sees it immediately, even offline /
    // if Firestore write is blocked.
    const nextLocal = [review, ...localReviews];
    setLocalReviews(nextLocal);
    saveLocalReviews(nextLocal);
    setJustPosted(true);
    setTimeout(() => setJustPosted(false), 4000);

    // Best-effort publish for everyone.
    if (window.fb) {
      try {
        await window.fb.db.collection('marquee_reviews').add({
          name: data.name, loc: data.loc, stars: data.stars, ea: data.ea, text: data.text,
          accent,
          createdAt: firebase.firestore.FieldValue.serverTimestamp(),
        });
      } catch (e) {
        // Local copy already shown; swallow so the user still feels success.
        console.warn('marquee publish failed (kept local):', e);
      }
    }
  }

  // Merge: newest local first, then Firestore, then seed list. De-dupe Firestore
  // rows that originated from this browser (same text) to avoid showing twice.
  const localTexts = new Set(localReviews.map(r => r.text));
  const fsFiltered = fsReviews.filter(r => !localTexts.has(r.text));
  const all = [...localReviews, ...fsFiltered, ...EFF_MARQUEE_REVIEWS];

  const half = Math.ceil(all.length / 2);
  const rowA = all.slice(0, half);
  const rowB = all.slice(half);

  return (
    <section className="section reviews-marquee-section" style={{ padding: '8px 0 72px' }}>
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">VERIFIED TRADERS</span>
          <h2 className="section-title mt-4">What traders are saying</h2>
          <p className="text-muted mt-3" style={{ maxWidth: 560 }}>Real feedback from licensed users running our top expert advisors live and on prop-firm accounts.</p>
        </div>
      </div>

      <div className="marquee-wrap">
        <MarqueeRow items={rowA} dir="left" speed={60}/>
        <MarqueeRow items={rowB} dir="right" speed={70}/>
      </div>

      <div className="container">
        <div className="flex-col" style={{ alignItems: 'center', marginTop: 36, gap: 12 }}>
          {justPosted && (
            <div className="panel" style={{ padding: '8px 14px', background: 'rgba(0,255,148,0.08)', borderColor: 'rgba(0,255,148,0.3)' }}>
              <span className="text-green font-mono text-xs">✓ Thanks! Your comment is now on the wall.</span>
            </div>
          )}
          <button className="btn btn-primary btn-lg btn-sheen" onClick={() => setModalOpen(true)}>
            ✎ Share your experience
          </button>
          <p className="text-xs text-muted">Used one of our EAs? Add your comment to the wall.</p>
          {adminOn && (
            <button className="btn btn-magenta btn-sm btn-sheen" style={{ marginTop: 6 }} onClick={() => setManageOpen(true)}>
              ⚙ Manage dropdown EAs (admin)
            </button>
          )}
        </div>
      </div>

      {modalOpen && (
        <AddCommentModal onClose={() => setModalOpen(false)} onSubmit={handleSubmit} eaOptions={eaOptions}/>
      )}
      {manageOpen && (
        <ManageDropdownModal onClose={() => setManageOpen(false)} allNames={allEaNames} hiddenSet={hiddenSet}/>
      )}
    </section>
  );
}

window.ReviewsMarquee = ReviewsMarquee;
