/* global React, window */
/* ============================================
   BrokersPage — recommended / partner brokers.
   Modern board with brand logos + account specs.
   Admin can edit everything via the broker editor.
   ============================================ */

function BrokerLogo({ broker, size = 46 }) {
  const color = broker.color || 'var(--cyan)';
  // Real uploaded logo → show image WITH the broker name beside it.
  if (broker.logoUrl) {
    return (
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, height: size }}>
        <img src={broker.logoUrl} alt={broker.name}
          style={{ maxHeight: size, maxWidth: 130, objectFit: 'contain', display: 'block', flexShrink: 0 }}/>
        <span className="broker-wordmark" style={{
          fontFamily: 'var(--font-display)', fontWeight: 800,
          letterSpacing: '-0.015em', color: 'var(--text)', whiteSpace: 'nowrap', lineHeight: 1,
        }}>{broker.name}</span>
      </div>
    );
  }
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 11, height: size }}>
      <span style={{
        width: 5, height: size * 0.62, borderRadius: 4, flexShrink: 0,
        background: color, boxShadow: `0 0 12px ${color}`,
      }}/>
      <span className="broker-wordmark" style={{
        fontFamily: 'var(--font-display)', fontWeight: 800,
        letterSpacing: '-0.015em', color: 'var(--text)', whiteSpace: 'nowrap',
        lineHeight: 1,
      }}>{broker.name}</span>
    </div>
  );
}

function BrokerCard({ broker }) {
  const color = broker.color || 'var(--cyan)';
  const specs = [
    { label: 'MIN DEPOSIT', value: broker.minDeposit, accent: 'var(--green)' },
    { label: 'MIN SPREAD', value: broker.minSpread, accent: 'var(--cyan)' },
    { label: 'MAX LEVERAGE', value: broker.leverage, accent: 'var(--amber)' },
  ];
  const openSignup = () => {
    if (broker.signupUrl) window.open(broker.signupUrl, '_blank', 'noopener');
  };
  return (
    <div className="panel panel-padded-lg lift broker-card" style={{
      position: 'relative', overflow: 'hidden',
      borderColor: 'var(--line)',
      display: 'flex', flexDirection: 'column', gap: 0,
    }}>
      {/* brand accent edge */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: `linear-gradient(90deg, ${color}, transparent)` }}/>
      {broker.featured && (
        <span className="font-mono" style={{
          position: 'absolute', top: 16, right: 16, fontSize: 9, letterSpacing: '0.12em',
          color: '#0b0e14', background: color, padding: '3px 8px', borderRadius: 5, fontWeight: 700,
        }}>TOP PICK</span>
      )}

      <BrokerLogo broker={broker} size={44} />
      {broker.instantWithdrawal && (
        <div className="instant-badge" style={{
          display: 'inline-flex', alignItems: 'center', gap: 6, alignSelf: 'flex-start',
          marginTop: 12, padding: '4px 10px', borderRadius: 999,
          background: 'rgba(0,255,148,0.10)', border: '1px solid rgba(0,255,148,0.4)',
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="var(--green)" stroke="none"><path d="M13 2L4.5 13.5H11l-1 8.5L19.5 10H13l0-8z"/></svg>
          <span className="font-mono" style={{ fontSize: 9.5, letterSpacing: '0.08em', color: 'var(--green)', fontWeight: 600 }}>INSTANT WITHDRAWALS</span>
        </div>
      )}
      <p className="text-muted text-sm mt-4" style={{ minHeight: 38 }}>{broker.tagline}</p>

      {broker.promo && (
        <div className="broker-promo promo-animated" style={{
          marginTop: 4, marginBottom: 4, padding: '10px 12px', borderRadius: 10,
          display: 'flex', alignItems: 'center', gap: 10,
          background: `linear-gradient(100deg, ${color}26, ${color}0d)`,
        }}>
          <span className="promo-gift" style={{
            width: 26, height: 26, borderRadius: 7, flexShrink: 0, display: 'grid', placeItems: 'center',
            background: 'linear-gradient(145deg, #ffd24a, #cd7f32)', color: '#3a2400',
          }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 12v10H4V12"/><path d="M2 7h20v5H2z"/><path d="M12 22V7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>
            <i className="promo-spark" style={{ top: '-4px', left: '50%', color: '#ffe9a3', '--dx': '5px', '--dy': '-9px', animationDelay: '0s' }}/>
            <i className="promo-spark" style={{ top: '50%', left: '-5px', color: '#cd7f32', '--dx': '-9px', '--dy': '-3px', animationDelay: '.35s' }}/>
            <i className="promo-spark" style={{ bottom: '-4px', right: '-3px', color: '#ffd24a', '--dx': '8px', '--dy': '8px', animationDelay: '.7s' }}/>
            <i className="promo-spark" style={{ top: '-3px', right: '-3px', color: '#cd7f32', '--dx': '9px', '--dy': '-8px', animationDelay: '1.05s' }}/>
            <i className="promo-spark" style={{ bottom: '-4px', left: '2px', color: '#fff7d6', '--dx': '-6px', '--dy': '9px', animationDelay: '.55s' }}/>
          </span>
          <div style={{ minWidth: 0 }}>
            <div className="font-mono promo-label" style={{ fontSize: 8, letterSpacing: '0.14em' }}>LIMITED OFFER</div>
            <div style={{ fontWeight: 700, fontSize: 13.5, marginTop: 2, lineHeight: 1.2 }}>{broker.promo}</div>
          </div>
        </div>
      )}

      {/* spec grid */}
      <div className="broker-spec-grid mt-5">
        {specs.map(s => (
          <div key={s.label} style={{
            background: 'rgba(0,0,0,0.28)', border: '1px solid var(--line-soft)',
            borderRadius: 10, padding: '12px 12px',
          }}>
            <div className="font-mono" style={{ fontSize: 8.5, letterSpacing: '0.12em', color: 'var(--text-3)' }}>{s.label}</div>
            <div style={{ fontWeight: 700, fontSize: 17, marginTop: 6, color: s.accent }}>{s.value || '—'}</div>
          </div>
        ))}
      </div>

      {/* account types */}
      <div className="mt-4">
        <div className="font-mono" style={{ fontSize: 8.5, letterSpacing: '0.12em', color: 'var(--text-3)', marginBottom: 8 }}>ACCOUNT TYPES</div>
        <div className="flex" style={{ flexWrap: 'wrap', gap: 6 }}>
          {String(broker.accounts || '').split('·').map(a => a.trim()).filter(Boolean).map((a, i) => (
            <span key={i} className="font-mono" style={{
              fontSize: 10.5, padding: '4px 9px', borderRadius: 6,
              background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line-soft)',
              color: 'var(--text-2)',
            }}>{a}</span>
          ))}
        </div>
      </div>

      {broker.regulation && (
        <div className="flex gap-2 mt-4" style={{ alignItems: 'center' }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--green)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>
          <span className="font-mono text-xs text-muted">{broker.regulation}</span>
        </div>
      )}

      <div style={{ flex: 1 }}/>
      <button
        onClick={openSignup}
        disabled={!broker.signupUrl}
        className="btn btn-lg btn-block mt-5"
        style={{
          background: broker.signupUrl ? color : 'rgba(255,255,255,0.05)',
          color: broker.signupUrl ? '#0b0e14' : 'var(--text-3)',
          fontWeight: 700, border: 'none',
          cursor: broker.signupUrl ? 'pointer' : 'not-allowed',
          boxShadow: broker.signupUrl ? `0 0 20px ${color}44` : 'none',
        }}>
        {broker.signupUrl ? 'Open account →' : 'Link coming soon'}
      </button>
    </div>
  );
}

function BrokersPage({ go }) {
  const [, setTick] = React.useState(0);
  const [adminOn, setAdminOn] = React.useState(!!window.__effAdminMode);
  const [editorOpen, setEditorOpen] = React.useState(false);

  React.useEffect(() => {
    const onChange = () => setTick(t => t + 1);
    const onAdmin = () => setAdminOn(!!window.__effAdminMode);
    window.addEventListener('eff_brokers_changed', onChange);
    window.addEventListener('eff_admin_changed', onAdmin);
    return () => {
      window.removeEventListener('eff_brokers_changed', onChange);
      window.removeEventListener('eff_admin_changed', onAdmin);
    };
  }, []);

  const brokers = window.Brokers?.getBrokers?.() || [];
  const intro = window.Brokers?.getIntro?.() || '';

  return (
    <div>
      {/* HERO */}
      <section style={{ padding: '64px 0 28px' }}>
        <div className="container">
          <div className="flex" style={{ justifyContent: 'space-between', alignItems: 'flex-end', gap: 24, flexWrap: 'wrap' }}>
            <div style={{ maxWidth: 720 }}>
              <span className="eyebrow">PARTNERS · BROKERS</span>
              <h1 className="mt-4" style={{ fontSize: 60, lineHeight: 1.02 }}>
                Recommended <span className="gradient-text">brokers</span>
              </h1>
              <p className="mt-6 text-muted" style={{ fontSize: 17, lineHeight: 1.6 }}>{intro}</p>
            </div>
            {adminOn && (
              <button className="btn btn-primary" onClick={() => setEditorOpen(true)}>
                ⚙ Edit brokers
              </button>
            )}
          </div>
        </div>
      </section>

      {/* BOARD */}
      <section className="section" style={{ paddingTop: 12 }}>
        <div className="container">
          <div className="brokers-grid" style={{ display: 'grid', gap: 20, alignItems: 'stretch' }}>
            {brokers.map(b => <BrokerCard key={b.id} broker={b} />)}
          </div>

          {brokers.length === 0 && (
            <div className="panel panel-padded-lg text-center text-muted">No brokers configured yet.</div>
          )}

          <p className="text-xs text-muted mt-8" style={{ maxWidth: 760, lineHeight: 1.6 }}>
            Risk warning: Trading forex and CFDs carries a high level of risk and may not be suitable for all investors.
            The brokers above are independent companies; we may receive a partner commission when you open an account through our links, at no extra cost to you.
          </p>
        </div>
      </section>

      {editorOpen && window.BrokerEditor && (
        <BrokerEditor onClose={() => setEditorOpen(false)} />
      )}
    </div>
  );
}

window.BrokersPage = BrokersPage;
