// AGENTFORGE-IA — Áreas sensibles de operación interna
const OPS_LABELS = {
  ops_finance: 'Finanzas',
  ops_sales: 'Ventas',
  ops_marketing: 'Marketing',
  ops_operations: 'Operaciones',
  ops_hr: 'RRHH',
  ops_support: 'Atención al cliente',
};

const DEFAULT_CONNECTORS = [
  'Google Workspace: Gmail',
  'Google Workspace: Drive',
  'Google Workspace: Calendar',
];

function InternalOpsArea({ areaId }) {
  const token = sessionStorage.getItem('af_token') || '';
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [objective, setObjective] = React.useState('');
  const [notes, setNotes] = React.useState('');
  const [rules, setRules] = React.useState([]);
  const [newRule, setNewRule] = React.useState('');
  const [connectors, setConnectors] = React.useState([]);
  const [newConnector, setNewConnector] = React.useState('');

  const readError = async (res, fallback) => {
    try {
      const payload = await res.json();
      if (payload && typeof payload.detail === 'string' && payload.detail.trim()) return payload.detail;
    } catch (_) {}
    return fallback;
  };

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/v1/internal-ops/areas/' + encodeURIComponent(areaId), {
        headers: { Authorization: 'Bearer ' + token },
      });
      if (!res.ok) {
        window.afNotify && window.afNotify(await readError(res, 'Sin permisos para esta área'));
        setLoading(false);
        return;
      }
      const data = await res.json();
      setObjective(data.objective || '');
      setNotes(data.notes || '');
      setRules(Array.isArray(data.rules) ? data.rules : []);
      const c = Array.isArray(data.connectors) ? data.connectors : [];
      setConnectors(c.length ? c : DEFAULT_CONNECTORS);
    } catch (_) {
      window.afNotify && window.afNotify('Error cargando configuración del área');
    } finally {
      setLoading(false);
    }
  }, [areaId, token]);

  React.useEffect(() => { load(); }, [load]);

  const save = async () => {
    setSaving(true);
    try {
      const res = await fetch('/api/v1/internal-ops/areas/' + encodeURIComponent(areaId), {
        method: 'PUT',
        headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
        body: JSON.stringify({
          objective,
          notes,
          rules,
          connectors,
        }),
      });
      if (!res.ok) {
        window.afNotify && window.afNotify(await readError(res, 'No se pudo guardar la configuración'));
        return;
      }
      window.afNotify && window.afNotify('Configuración guardada');
    } catch (_) {
      window.afNotify && window.afNotify('Error de red al guardar');
    } finally {
      setSaving(false);
    }
  };

  const seedDemo = async () => {
    try {
      const res = await fetch('/api/v1/internal-ops/seed-demo', {
        method: 'POST',
        headers: { Authorization: 'Bearer ' + token },
      });
      if (!res.ok) {
        window.afNotify && window.afNotify(await readError(res, 'No se pudo cargar la demo'));
        return;
      }
      window.afNotify && window.afNotify('Datos demo cargados en todas las áreas');
      await load();
    } catch (_) {
      window.afNotify && window.afNotify('Error de red al cargar demo');
    }
  };

  if (loading) {
    return <div className="card card-pad">Cargando área operativa…</div>;
  }

  return (
    <div>
      <div className="page-head">
        <h1>Operación interna: {OPS_LABELS[areaId] || areaId}</h1>
        <span className="crumbs mono">rol sensible · edición protegida</span>
        <div className="actions">
          <button className="btn" onClick={seedDemo}>
            <Icon name="sparkles" size={12} /> Cargar demo completa
          </button>
          <button className="btn btn-primary" onClick={save} disabled={saving}>
            <Icon name="check" size={12} /> {saving ? 'Guardando…' : 'Guardar cambios'}
          </button>
        </div>
      </div>

      <div className="section" style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 12 }}>
        <div className="card card-pad">
          <div style={{ fontWeight: 700, marginBottom: 8 }}>Objetivo del área</div>
          <textarea className="textarea" rows={3} value={objective} onChange={(e) => setObjective(e.target.value)} />
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 8 }}>
            Aquí defines para qué sirve esta área y qué resultado debe entregar.
          </div>
        </div>

        <div className="card card-pad">
          <div style={{ fontWeight: 700, marginBottom: 8 }}>Conectores recomendados</div>
          <div style={{ display: 'grid', gap: 6 }}>
            {connectors.map((c, i) => (
              <div key={i} style={{ display: 'flex', gap: 6 }}>
                <input className="input" value={c} onChange={(e) => setConnectors((prev) => prev.map((x, idx) => idx === i ? e.target.value : x))} />
                <button className="btn btn-ghost btn-sm" onClick={() => setConnectors((prev) => prev.filter((_, idx) => idx !== i))}>✕</button>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
            <input className="input" placeholder="Añadir conector (ej: Google Workspace: Gmail)" value={newConnector} onChange={(e) => setNewConnector(e.target.value)} />
            <button className="btn btn-sm" onClick={() => {
              const v = newConnector.trim();
              if (!v) return;
              setConnectors((prev) => [...prev, v]);
              setNewConnector('');
            }}>
              <Icon name="plus" size={11} />
            </button>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 8 }}>
            Alternativa elegida: priorizar Google Workspace (Gmail/Drive/Calendar) para operación interna segura y centralizada.
          </div>
        </div>
      </div>

      <div className="section" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div className="card card-pad">
          <div style={{ fontWeight: 700, marginBottom: 8 }}>Reglas de operación (editables)</div>
          <div style={{ display: 'grid', gap: 8 }}>
            {rules.map((r, i) => (
              <div key={i} style={{ display: 'flex', gap: 6 }}>
                <textarea className="textarea" rows={2} value={r} onChange={(e) => setRules((prev) => prev.map((x, idx) => idx === i ? e.target.value : x))} />
                <button className="btn btn-ghost btn-sm" onClick={() => setRules((prev) => prev.filter((_, idx) => idx !== i))}>✕</button>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
            <textarea className="textarea" rows={2} placeholder="Nueva regla…" value={newRule} onChange={(e) => setNewRule(e.target.value)} />
            <button className="btn btn-sm" onClick={() => {
              const v = newRule.trim();
              if (!v) return;
              setRules((prev) => [...prev, v]);
              setNewRule('');
            }}>
              <Icon name="plus" size={11} />
            </button>
          </div>
        </div>

        <div className="card card-pad">
          <div style={{ fontWeight: 700, marginBottom: 8 }}>Notas y datos adicionales</div>
          <textarea className="textarea" rows={18} value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Añade instrucciones internas, excepciones, datos sensibles de proceso, etc." />
        </div>
      </div>
    </div>
  );
}

window.InternalOpsArea = InternalOpsArea;
