/* global React */
/* ============================================
   EAEditor — Admin modal to edit or CREATE EA
   ============================================ */
function EAEditor({ ea, onClose, isNew = false }) {
  const fields = [
    { key: 'name', label: 'Name', type: 'text' },
    { key: 'tagline', label: 'Tagline (short description)', type: 'textarea' },
    { key: 'strategy', label: 'Strategy', type: 'text' },
    { key: 'pairs', label: 'Pairs (comma-separated)', type: 'pairs' },
    { key: 'price', label: 'Price (USD)', type: 'number' },
    { key: 'badge', label: 'Badge (optional)', type: 'text' },
    { key: 'winRate', label: 'Win Rate %', type: 'number', step: 0.1 },
    { key: 'pf', label: 'Profit Factor', type: 'number', step: 0.01 },
    { key: 'dd', label: 'Max Drawdown %', type: 'number', step: 0.1 },
    { key: 'risk', label: 'Risk Score (1-10)', type: 'number', step: 0.1 },
    { key: 'users', label: 'Active users', type: 'number' },
    { key: 'trades', label: 'Total trades', type: 'number' },
    { key: 'age', label: 'Live age (e.g. "12 months")', type: 'text' },
    { key: 'overviewDescription', label: 'OVERVIEW · Strategy description (long)', type: 'textarea' },
    { key: 'parametersText', label: 'PARAMETERS · .set file preview (raw text)', type: 'textarea', rows: 8 },
  ];

  // For NEW EA, also need an ID
  const [newId, setNewId] = React.useState('');

  const [vals, setVals] = React.useState(() => {
    const init = {};
    fields.forEach(f => {
      let v = ea?.[f.key];
      if (f.type === 'pairs' && Array.isArray(v)) v = v.join(', ');
      init[f.key] = v == null ? '' : String(v);
    });
    return init;
  });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);

  function setField(key, value) { setVals(v => ({ ...v, [key]: value })); }

  // Auto-suggest ID from name for new EAs
  React.useEffect(() => {
    if (isNew && vals.name && !newId) {
      const slug = vals.name.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 20);
      setNewId(slug);
    }
  }, [vals.name, isNew]);

  async function save() {
    setError(''); setSaving(true); setSuccess(false);
    try {
      const eaId = isNew ? newId.trim() : ea.id;
      if (isNew && !eaId) throw new Error('ID is required');
      if (isNew && !/^[a-z0-9_-]+$/.test(eaId)) throw new Error('ID must be lowercase letters/numbers only');

      const payload = {};
      fields.forEach(f => {
        let v = vals[f.key];
        if (v === '' || v == null) {
          payload[f.key] = isNew ? null : null;
          return;
        }
        if (f.type === 'number') {
          const n = parseFloat(v);
          if (!isNaN(n)) payload[f.key] = n;
        } else if (f.type === 'pairs') {
          payload[f.key] = String(v).split(',').map(s => s.trim()).filter(Boolean);
        } else {
          payload[f.key] = v;
        }
      });
      if (isNew) payload.isCustom = true;
      await window.EAReports.saveEAFields(eaId, payload);
      setSuccess(true);
      setTimeout(onClose, 800);
    } catch (e) {
      setError(e.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  async function reset() {
    if (!confirm(isNew ? 'Cancel creation?' : 'Reset all overrides for this EA?')) return;
    setError(''); setSaving(true);
    try {
      if (!isNew) await window.EAReports.resetEA(ea.id);
      setSuccess(true);
      setTimeout(onClose, 600);
    } catch (e) {
      setError(e.message);
    } finally {
      setSaving(false);
    }
  }

  return (
    <Modal onClose={onClose}>
      <div style={{ width: '100%', maxWidth: 600 }}>
        <div className="flex-between mb-4">
          <div>
            <span className="eyebrow" style={{ color: 'var(--magenta)' }}>ADMIN · {isNew ? 'CREATE NEW EA' : 'EDIT EA'}</span>
            <h2 className="mt-2" style={{ fontSize: 22 }}>{isNew ? 'New Expert Advisor' : ea.name}</h2>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm">×</button>
        </div>

        <div style={{ maxHeight: '60vh', overflowY: 'auto', paddingRight: 8 }}>
          {isNew && (
            <div className="field mb-3">
              <label>EA ID (URL slug · lowercase, no spaces)</label>
              <input className="input font-mono" value={newId} onChange={e => setNewId(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, ''))} placeholder="e.g. apex, quantum, ..."/>
            </div>
          )}
          {fields.map(f => (
            <div key={f.key} className="field mb-3">
              <label>{f.label}</label>
              {f.type === 'textarea' ? (
                <textarea className="input" rows={f.rows || 3} value={vals[f.key]} onChange={e => setField(f.key, e.target.value)} placeholder={f.key === 'parametersText' ? 'RiskPerTrade=1.0\nLotSize=0.01\nStopLoss=250\n...' : ''}/>
              ) : (
                <input
                  className="input"
                  type={f.type === 'number' ? 'number' : 'text'}
                  step={f.step}
                  value={vals[f.key]}
                  onChange={e => setField(f.key, e.target.value)}
                />
              )}
            </div>
          ))}
        </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">
          {!isNew && <button className="btn btn-ghost" onClick={reset} disabled={saving} style={{ color: 'var(--red)' }}>Reset</button>}
          <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> : (isNew ? 'Create & publish' : 'Save & publish')}
          </button>
        </div>
      </div>
    </Modal>
  );
}

window.EAEditor = EAEditor;
