// Page 7 — Configuration

function ConfigPage({ pushToast }) {
  const [config, setConfig] = useState(() => TEAM.map(t => ({
    id: t.id,
    name: t.name,
    handle: `@${t.id}`,
    role: t.role,
    email: t.email,
    envKey: t.envKey,
    planeUserId: t.planeUserId,
    modules: [...t.modulesCurrent, ...t.modulesHistorical.slice(0, 2).map(h => h.module)].filter((v, i, a) => a.indexOf(v) === i),
    enabled: t.enabled,
  })));

  const [poll, setPoll] = useState(30);
  const [confirm, setConfirm] = useState(null);
  const [tg, setTg] = useState({
    token: "8174583291:AAFxxxx****REDACTED****",
    chatId: "-1001234567890",
    enabled: true,
  });

  const setAgentField = (id, field, val) => {
    setConfig((c) => c.map(r => r.id === id ? { ...r, [field]: val } : r));
  };

  const addModule = (id, mod) => {
    if (!mod) return;
    setConfig((c) => c.map(r => r.id === id ? { ...r, modules: r.modules.includes(mod) ? r.modules : [...r.modules, mod] } : r));
  };
  const removeModule = (id, mod) => {
    setConfig((c) => c.map(r => r.id === id ? { ...r, modules: r.modules.filter(m => m !== mod) } : r));
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Конфигурация</h1>
          <div className="page-sub">Edit'ы пишут в <span className="mono">config/agents.yaml</span>. После Save watchdog перечитает конфиг автоматически.</div>
        </div>
      </div>

      {/* Agents */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div className="card-hd">
          <h3>Агенты · <span className="mono" style={{ textTransform: "none", color: "var(--text-muted)" }}>config/agents.yaml</span></h3>
          <span className="muted" style={{ fontSize: 11 }}>{config.length} строк</span>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 100 }}>Имя</th>
              <th style={{ width: 90 }}>Handle</th>
              <th style={{ width: 110 }}>Роль</th>
              <th>Email</th>
              <th>API-ключ (env)</th>
              <th style={{ width: 130 }}>plane_user_id</th>
              <th>Модули</th>
              <th style={{ width: 110, textAlign: "right" }}>Watcher</th>
            </tr>
          </thead>
          <tbody>
            {config.map((row) => (
              <tr key={row.id}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <Avatar agentId={row.id} size={26} />
                    <input className="input" style={{ width: 90, padding: "4px 8px", fontSize: 13 }} value={row.name} onChange={(e) => setAgentField(row.id, "name", e.target.value)} />
                  </div>
                </td>
                <td><input className="input mono" style={{ width: 80, padding: "4px 8px", fontSize: 12 }} value={row.handle} onChange={(e) => setAgentField(row.id, "handle", e.target.value)} /></td>
                <td>
                  <select className="input" style={{ width: 100, padding: "4px 8px", fontSize: 12 }} value={row.role} onChange={(e) => setAgentField(row.id, "role", e.target.value)}>
                    {["architect","coder","reviewer","tester","scout","workflow-lead"].map(r => <option key={r} value={r}>{r}</option>)}
                  </select>
                </td>
                <td><input className="input mono" style={{ width: "100%", padding: "4px 8px", fontSize: 12 }} value={row.email} onChange={(e) => setAgentField(row.id, "email", e.target.value)} /></td>
                <td><input className="input mono" style={{ width: "100%", padding: "4px 8px", fontSize: 12 }} value={row.envKey} onChange={(e) => setAgentField(row.id, "envKey", e.target.value)} /></td>
                <td><span className="mono muted" style={{ fontSize: 11 }}>{row.planeUserId}</span></td>
                <td>
                  <ModulesEditor
                    modules={row.modules}
                    onAdd={(m) => addModule(row.id, m)}
                    onRemove={(m) => removeModule(row.id, m)}
                  />
                </td>
                <td style={{ textAlign: "right" }}>
                  <label className="toggle">
                    <input type="checkbox" checked={row.enabled} onChange={(e) => setAgentField(row.id, "enabled", e.target.checked)} />
                    <span className="track" /><span className="thumb" />
                  </label>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Two columns: alerts + watchdog */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 20 }}>
        <div className="card">
          <div className="card-hd"><h3>Алерт-каналы</h3></div>
          <div className="card-bd">
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="#27a7e7"><path d="M9.78 18.65l.28-4.23 7.68-6.92c.34-.31-.07-.46-.52-.19L7.74 13.3 3.64 12c-.88-.25-.89-.86.2-1.3l15.97-6.16c.73-.33 1.43.18 1.15 1.3l-2.72 12.81c-.19.91-.74 1.13-1.5.71L12.6 16.3l-1.99 1.93c-.23.23-.42.42-.83.42z"/></svg>
              <span style={{ fontSize: 14, fontWeight: 600 }}>Telegram-бот</span>
              <span className="ml-auto" />
              <label className="toggle">
                <input type="checkbox" checked={tg.enabled} onChange={(e) => setTg({ ...tg, enabled: e.target.checked })} />
                <span className="track" /><span className="thumb" />
              </label>
            </div>
            <Field label="Token">
              <input className="input mono" type="password" value={tg.token} onChange={(e) => setTg({ ...tg, token: e.target.value })} style={{ width: "100%", fontSize: 12 }} />
            </Field>
            <Field label="Chat ID">
              <input className="input mono" value={tg.chatId} onChange={(e) => setTg({ ...tg, chatId: e.target.value })} style={{ width: "100%", fontSize: 12 }} />
            </Field>
            <button className="btn" onClick={() => pushToast("Тестовое сообщение отправлено в Telegram", "ok")} style={{ marginTop: 6 }}>
              📤 Отправить тестовое
            </button>

            <div style={{ marginTop: 20, padding: 12, background: "var(--bg-elev)", borderRadius: 6, border: "1px dashed var(--border-soft)", display: "flex", alignItems: "center", gap: 10 }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" strokeWidth="2"><path d="M22 6 12 13 2 6"/><rect x="2" y="4" width="20" height="16" rx="2"/></svg>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13 }}>Email</div>
                <div className="muted" style={{ fontSize: 11 }}>SMTP для нотификаций</div>
              </div>
              <span className="pill neutral">coming soon</span>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-hd"><h3>Watchdog</h3></div>
          <div className="card-bd">
            <Field label="Polling interval (секунд)">
              <input className="input mono" type="number" min="5" step="5" value={poll} onChange={(e) => setPoll(parseInt(e.target.value) || 30)} style={{ width: 120, fontSize: 13 }} />
              <span className="muted" style={{ fontSize: 12, marginLeft: 10 }}>текущее: каждые {poll}с</span>
            </Field>
            <Field label="Cutoff timestamp">
              <div className="mono" style={{ fontSize: 12, color: "var(--text-muted)", padding: "6px 0" }}>
                2026-05-10T00:00:00Z
                <span className="pill neutral" style={{ marginLeft: 8 }}>read-only</span>
              </div>
              <div className="muted" style={{ fontSize: 11 }}>События до этой метки не обрабатываются.</div>
            </Field>
            <Field label="Baseline">
              <button className="btn btn-danger" onClick={() => setConfirm("baseline")}>↺ Сбросить baseline</button>
              <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>
                Сбрасывает «известное состояние» Plane. Все текущие задачи будут пере-обработаны.
              </div>
            </Field>

            <div style={{ marginTop: 16, padding: 12, background: "var(--bg-elev)", borderRadius: 6, border: "1px solid var(--border-soft)" }}>
              <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 8 }}>Источник</div>
              <div className="mono" style={{ fontSize: 12 }}>
                <div><span className="muted">PLANE_URL</span> = https://plane.multi-print.local</div>
                <div><span className="muted">WORKSPACE</span> = multi-print</div>
                <div><span className="muted">PROJECT</span> = PriceBot</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Save bar */}
      <div style={{
        position: "sticky", bottom: 16,
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "14px 20px",
        background: "var(--surface)", border: "1px solid var(--accent)",
        borderRadius: 10, boxShadow: "0 8px 24px rgba(0,0,0,0.4)",
      }}>
        <div style={{ fontSize: 13 }}>
          <span style={{ color: "var(--accent)" }}>●</span>
          <span style={{ marginLeft: 8 }}>Несохранённые изменения в config/agents.yaml</span>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn">Сбросить</button>
          <button className="btn btn-primary" onClick={() => pushToast("Конфигурация сохранена. Watchdog перечитан.", "ok")}>💾 Сохранить</button>
        </div>
      </div>

      <ConfirmDialog
        open={confirm === "baseline"}
        title="Сбросить baseline?"
        message="Все текущие 50+ задач Plane будут пере-обработаны watchdog'ом как новые. Это вызовет всплеск алертов (warning), но не сломает данные."
        danger
        onCancel={() => setConfirm(null)}
        onConfirm={() => { setConfirm(null); pushToast("Baseline сброшен. Watchdog обрабатывает 47 задач…", "warn"); }}
      />
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 12 }}>
      <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 4 }}>{label}</div>
      {children}
    </div>
  );
}

function ModulesEditor({ modules, onAdd, onRemove }) {
  const [draft, setDraft] = useState("");
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 4, alignItems: "center" }}>
      {modules.map((m) => (
        <span key={m} style={{
          display: "inline-flex", alignItems: "center", gap: 4,
          padding: "2px 4px 2px 8px", borderRadius: 4,
          fontSize: 11, fontFamily: "var(--font-mono)",
          color: moduleColor(m), background: "rgba(255,255,255,0.05)",
          border: `1px solid ${moduleColor(m)}33`,
        }}>
          {m}
          <button onClick={() => onRemove(m)} className="btn btn-ghost" style={{ padding: "0 4px", fontSize: 12, color: "var(--text-muted)", border: "none", background: "transparent" }}>×</button>
        </span>
      ))}
      <input
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === "Enter" && draft.trim()) {
            onAdd(draft.trim());
            setDraft("");
          }
        }}
        placeholder="+ модуль"
        className="input mono"
        style={{ width: 90, padding: "2px 6px", fontSize: 11 }}
      />
    </div>
  );
}

window.ConfigPage = ConfigPage;
