/* global React, firebase */
/* ============================================
   EAOverviewEditor — Admin modal to edit the Overview tab content
   Stores these fields on /eas/{eaId}:
     overviewDescription : string   (How it works)
     specs               : [{ k, v }]   (Specifications table)
     included            : [string]      (What's included list)
     users / trades / age                (Social proof — reused)
   ============================================ */
function EAOverviewEditor({ ea, onClose }) {
  const DEFAULT_SPECS = [
    { k: 'Platform', v: 'MetaTrader 5' },
    { k: 'Timeframe', v: 'H1 / H4' },
    { k: 'Min Deposit', v: '$500' },
    { k: 'Recommended', v: '$2,000+' },
    { k: 'Broker Type', v: 'ECN / Raw Spread' },
    { k: 'Leverage', v: '1:100 → 1:500' },
    { k: 'VPS Required', v: 'Recommended for 24/7' },
  ];
  const DEFAULT_INCLUDED = [
    'Compiled .ex5 file (lifetime license)',
    '.set files for each supported pair',
    'Full backtest report (PDF + .csv)',
    'AI Agent profile for this EA',
    'Setup video walkthrough (12 min)',
    'Priority support · 24h response',
    'Free lifetime updates',
  ];

  const [desc, setDesc] = React.useState(ea.overviewDescription || '');
  const [specs, setSpecs] = React.useState(
    (Array.isArray(ea.specs) && ea.specs.length ? ea.specs : DEFAULT_SPECS).map(s => ({ k: s.k ?? '', v: s.v ?? '' }))
  );
  const [included, setIncluded] = React.useState(
    Array.isArray(ea.included) && ea.included.length ? [...ea.included] : DEFAULT_INCLUDED
  );
  const [users, setUsers] = React.useState(ea.users ?? '');
  const [trades, setTrades] = React.useState(ea.trades ?? '');
  const [age, setAge] = React.useState(ea.age ?? '');

  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);

  // Spec helpers
  const setSpec = (i, key, val) => setSpecs(l => l.map((s, idx) => idx === i ? { ...s, [key]: val } : s));
  const addSpec = () => setSpecs(l => [...l, { k: 'New row', v: '' }]);
  const removeSpec = i => setSpecs(l => l.filter((_, idx) => idx !== i));
  // Included helpers
  const setInc = (i, val) => setIncluded(l => l.map((s, idx) => idx === i ? val : s));
  const addInc = () => setIncluded(l => [...l, 'New item']);
  const removeInc = i => setIncluded(l => l.filter((_, idx) => idx !== i));

  async function save() {
    setError(''); setSaving(true); setSuccess(false);
    try {
      const cleanSpecs = specs
        .map(s => ({ k: String(s.k || '').trim(), v: String(s.v || '').trim() }))
        .filter(s => s.k || s.v);
      const cleanIncluded = included.map(s => String(s || '').trim()).filter(Boolean);
      const payload = {
        overviewDescription: desc.trim() || null,
        specs: cleanSpecs,
        included: cleanIncluded,
      };
      const nu = parseInt(users, 10); if (!isNaN(nu)) payload.users = nu;
      const nt = parseInt(trades, 10); if (!isNaN(nt)) payload.trades = nt;
      if (String(age).trim()) payload.age = String(age).trim();

      await window.EAReports.saveEAFields(ea.id, payload);
      setSuccess(true);
      setTimeout(onClose, 800);
    } catch (e) {
      setError(e.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  return (
    <Modal onClose={onClose}>
      <div style={{ width: '100%', maxWidth: 640 }}>
        <div className="flex-between mb-4">
          <div>
            <span className="eyebrow" style={{ color: 'var(--magenta)' }}>ADMIN · EDIT OVERVIEW · v1</span>
            <h2 className="mt-2" style={{ fontSize: 22 }}>{ea.name} · Overview</h2>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm">×</button>
        </div>

        <div style={{ maxHeight: '62vh', overflowY: 'auto', paddingRight: 8 }}>
          {/* Strategy text */}
          <div className="field mb-4">
            <label>How it works (strategy description)</label>
            <textarea className="input" rows={5} value={desc} onChange={e => setDesc(e.target.value)}
              placeholder="Describe how this EA works…"/>
          </div>

          {/* Specifications */}
          <div className="field mb-4">
            <label>Specifications</label>
            <div className="flex-col gap-2">
              {specs.map((s, i) => (
                <div key={i} className="flex gap-2" style={{ alignItems: 'center' }}>
                  <input className="input" style={{ flex: 1 }} placeholder="Label" value={s.k} onChange={e => setSpec(i, 'k', e.target.value)}/>
                  <input className="input font-mono" style={{ flex: 1 }} placeholder="Value" value={s.v} onChange={e => setSpec(i, 'v', e.target.value)}/>
                  <button type="button" className="btn btn-ghost btn-sm" onClick={() => removeSpec(i)} style={{ color: 'var(--red)', flexShrink: 0 }}>×</button>
                </div>
              ))}
              <button type="button" className="btn btn-secondary btn-sm" onClick={addSpec} style={{ alignSelf: 'flex-start' }}>+ Add row</button>
            </div>
          </div>

          {/* What's included */}
          <div className="field mb-4">
            <label>What's included</label>
            <div className="flex-col gap-2">
              {included.map((item, i) => (
                <div key={i} className="flex gap-2" style={{ alignItems: 'center' }}>
                  <span style={{ color: 'var(--green)', fontFamily: 'var(--font-mono)', flexShrink: 0 }}>✓</span>
                  <input className="input" style={{ flex: 1 }} placeholder="Included item" value={item} onChange={e => setInc(i, e.target.value)}/>
                  <button type="button" className="btn btn-ghost btn-sm" onClick={() => removeInc(i)} style={{ color: 'var(--red)', flexShrink: 0 }}>×</button>
                </div>
              ))}
              <button type="button" className="btn btn-secondary btn-sm" onClick={addInc} style={{ alignSelf: 'flex-start' }}>+ Add item</button>
            </div>
          </div>

          {/* Social proof */}
          <div className="field mb-2">
            <label>Social proof</label>
            <div className="flex gap-2" style={{ flexWrap: 'wrap' }}>
              <div style={{ flex: '1 1 120px' }}>
                <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Active users</div>
                <input className="input" type="number" min="0" value={users} onChange={e => setUsers(e.target.value)} style={{ width: '100%' }}/>
              </div>
              <div style={{ flex: '1 1 120px' }}>
                <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Total trades</div>
                <input className="input" type="number" min="0" value={trades} onChange={e => setTrades(e.target.value)} style={{ width: '100%' }}/>
              </div>
              <div style={{ flex: '1 1 120px' }}>
                <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>In production</div>
                <input className="input" value={age} onChange={e => setAge(e.target.value)} placeholder="22 months" style={{ width: '100%' }}/>
              </div>
            </div>
          </div>
        </div>

        {error && <div className="strat-pdf-error" style={{ marginTop: 12 }}>⚠ {error}</div>}

        <div className="flex gap-2 mt-4">
          <button className="btn btn-primary btn-block" onClick={save} disabled={saving}>
            {success ? '✓ Saved' : saving ? 'Saving…' : 'Save & publish'}
          </button>
          <button className="btn btn-ghost" onClick={onClose} disabled={saving}>Cancel</button>
        </div>
      </div>
    </Modal>
  );
}

window.EAOverviewEditor = EAOverviewEditor;
