/* global React, window */
/* ============================================
   BrokerEditor — Admin modal to edit ALL broker
   data: name, colour, specs, signup links, intro
   text, ordering, add/remove brokers.
   Saves to Firestore → live for every visitor.
   ============================================ */

const BROKER_FIELDS = [
  { key: 'tagline',    label: 'Tagline',          ph: 'Short selling point' },
  { key: 'promo',      label: 'Promo / bonus offer (leave blank for none)', ph: '50% deposit bonus — up to $100', wide: true },
  { key: 'minDeposit', label: 'Min deposit',      ph: '$10' },
  { key: 'minSpread',  label: 'Min spread',       ph: '0.0 pips' },
  { key: 'leverage',   label: 'Max leverage',     ph: 'Up to 1:500' },
  { key: 'accounts',   label: 'Account types (· separated)', ph: 'Standard · Pro · Raw', wide: true },
  { key: 'regulation', label: 'Regulation',       ph: 'FCA · CySEC' },
  { key: 'signupUrl',  label: 'Registration link (your affiliate URL)', ph: 'https://...', wide: true },
  { key: 'logoUrl',    label: 'Logo image URL (optional — leave blank for wordmark)', ph: 'https://...', wide: true },
];

const COLOR_SWATCHES = ['#F3D000', '#E4002B', '#0A66C2', '#C8102E', '#00B9A9', '#7C5CFF', '#00E5FF', '#FF2DAA'];

function newBrokerId() {
  return 'broker_' + Math.random().toString(36).slice(2, 8);
}

function BrokerEditor({ onClose }) {
  const [list, setList] = React.useState(() => (window.Brokers?.getBrokers?.() || []).map(b => ({ ...b })));
  const [intro, setIntro] = React.useState(() => window.Brokers?.getIntro?.() || '');
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);
  const [openId, setOpenId] = React.useState(list[0]?.id || null);

  function setField(id, key, value) {
    setList(l => l.map(b => b.id === id ? { ...b, [key]: value } : b));
  }
  function move(i, dir) {
    setList(l => {
      const j = i + dir;
      if (j < 0 || j >= l.length) return l;
      const copy = [...l];
      [copy[i], copy[j]] = [copy[j], copy[i]];
      return copy;
    });
  }
  function removeBroker(id) {
    if (!confirm('Remove this broker?')) return;
    setList(l => l.filter(b => b.id !== id));
  }
  function addBroker() {
    const b = {
      id: newBrokerId(), name: 'New Broker', color: '#00E5FF',
      tagline: '', minDeposit: '', accounts: '', minSpread: '',
      leverage: '', regulation: '', signupUrl: '', logoUrl: '', featured: false, promo: '', instantWithdrawal: false,
    };
    setList(l => [...l, b]);
    setOpenId(b.id);
  }

  async function save() {
    setError(''); setSaving(true); setSuccess(false);
    try {
      const clean = list.map(b => ({
        id: b.id || newBrokerId(),
        name: (b.name || '').trim() || 'Untitled',
        color: b.color || '#00E5FF',
        tagline: b.tagline || '',
        promo: b.promo || '',
        minDeposit: b.minDeposit || '',
        accounts: b.accounts || '',
        minSpread: b.minSpread || '',
        leverage: b.leverage || '',
        regulation: b.regulation || '',
        signupUrl: (b.signupUrl || '').trim(),
        logoUrl: (b.logoUrl || '').trim(),
        instantWithdrawal: !!b.instantWithdrawal,
        featured: !!b.featured,
      }));
      await window.Brokers.saveBrokers(clean, intro);
      setSuccess(true);
      setTimeout(onClose, 800);
    } catch (e) {
      setError(e.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  return (
    <Modal onClose={onClose}>
      <div style={{ width: '100%', maxWidth: 860 }}>
        <div className="flex-between mb-4">
          <div>
            <span className="eyebrow" style={{ color: 'var(--magenta)' }}>ADMIN · BROKERS</span>
            <h2 className="mt-2" style={{ fontSize: 22 }}>Edit recommended brokers</h2>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm">×</button>
        </div>

        <div style={{ maxHeight: '78vh', overflowY: 'auto', paddingRight: 8 }}>
          {/* Intro copy */}
          <div className="field mb-4">
            <label>Intro / recommendation text</label>
            <textarea className="input" rows="3" value={intro} onChange={e => setIntro(e.target.value)}
              placeholder="Why you recommend these brokers"/>
          </div>

          <div className="divider" style={{ margin: '8px 0 16px' }}/>

          <div className="flex-col gap-3">
            {list.map((b, i) => {
              const open = openId === b.id;
              return (
                <div key={b.id} style={{ border: '1px solid var(--line)', borderRadius: 12, background: 'rgba(255,255,255,0.02)', overflow: 'hidden' }}>
                  {/* row header */}
                  <div className="flex gap-2" style={{ alignItems: 'center', padding: '10px 12px' }}>
                    <span style={{ width: 22, height: 22, borderRadius: 6, background: b.color, flexShrink: 0, boxShadow: `0 0 10px ${b.color}66` }}/>
                    <div style={{ flex: 1, minWidth: 0, cursor: 'pointer' }} onClick={() => setOpenId(open ? null : b.id)}>
                      <div style={{ fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{b.name}{b.featured ? '  ★' : ''}</div>
                    </div>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => move(i, -1)} disabled={i === 0} style={{ padding: '4px 8px' }}>↑</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => move(i, 1)} disabled={i === list.length - 1} style={{ padding: '4px 8px' }}>↓</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpenId(open ? null : b.id)} style={{ padding: '4px 8px' }}>{open ? '▲' : '▼'}</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => removeBroker(b.id)} style={{ padding: '4px 8px', color: 'var(--red)' }}>×</button>
                  </div>

                  {open && (
                    <div style={{ padding: '4px 12px 14px' }}>
                      <div className="field mb-3">
                        <label>Broker name</label>
                        <input className="input" value={b.name} onChange={e => setField(b.id, 'name', e.target.value)} placeholder="Broker name"/>
                      </div>

                      {/* brand colour */}
                      <div className="field mb-3">
                        <label>Brand colour</label>
                        <div className="flex gap-2" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
                          {COLOR_SWATCHES.map(c => (
                            <button key={c} type="button" onClick={() => setField(b.id, 'color', c)}
                              style={{ width: 26, height: 26, borderRadius: 7, background: c, cursor: 'pointer',
                                border: b.color === c ? '2px solid #fff' : '2px solid transparent', boxShadow: `0 0 8px ${c}66` }}/>
                          ))}
                          <input type="color" value={b.color} onChange={e => setField(b.id, 'color', e.target.value)}
                            style={{ width: 34, height: 28, border: 'none', background: 'none', cursor: 'pointer' }}/>
                        </div>
                      </div>

                      {/* featured + instant-withdrawal toggles */}
                      <div className="field mb-3">
                        <label className="flex gap-2" style={{ alignItems: 'center', cursor: 'pointer' }}>
                          <input type="checkbox" checked={!!b.featured} onChange={e => setField(b.id, 'featured', e.target.checked)}/>
                          <span>Mark as “Top pick” (highlighted badge)</span>
                        </label>
                      </div>
                      <div className="field mb-3">
                        <label className="flex gap-2" style={{ alignItems: 'center', cursor: 'pointer' }}>
                          <input type="checkbox" checked={!!b.instantWithdrawal} onChange={e => setField(b.id, 'instantWithdrawal', e.target.checked)}/>
                          <span>Offers instant withdrawals (⚡ badge)</span>
                        </label>
                      </div>

                      <div className="grid grid-2" style={{ gap: 12 }}>
                        {BROKER_FIELDS.map(f => (
                          <div className="field" key={f.key} style={f.wide ? { gridColumn: '1 / -1' } : null}>
                            <label>{f.label}</label>
                            <input className="input" value={b[f.key] || ''} onChange={e => setField(b.id, f.key, e.target.value)} placeholder={f.ph}/>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          <button type="button" className="btn btn-secondary mt-4" onClick={addBroker}>+ Add broker</button>
        </div>

        {error && <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">⚠ {error}</span></div>}
        {success && <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>
  );
}

window.BrokerEditor = BrokerEditor;
