/* Wa by Elivate — Settings / safety guardrails */

function Row({ title, desc, children }) {
  return (
    <div className="set-row">
      <div className="set-row-text"><div className="set-row-title">{title}</div><div className="set-row-desc">{desc}</div></div>
      <div className="set-row-control">{children}</div>
    </div>
  );
}

function SettingsScreen({ go }) {
  const [s, setS] = React.useState({ throttleEnabled: true, dedicatedNumber: true, hourlyCap: 80, dailyCap: 400, optInOnly: true, backoffOnErrors: true, autoReconnect: true, apiBaseUrl: "", webhookUrl: "" });
  const [status, setStatus] = React.useState({});
  const [openaiKey, setOpenaiKey] = React.useState("");
  const [openaiContext, setOpenaiContext] = React.useState("");
  const [saved, setSaved] = React.useState("");

  React.useEffect(() => {
    window.WaApi.settings().then(setS).catch(() => {});
    window.WaApi.status().then(setStatus).catch(() => {});
    window.WaApi.openaiContext().then(setOpenaiContext).catch(() => {});
  }, []);

  const save = async (patch) => {
    const next = { ...s, ...patch };
    setS(next);
    setS(await window.WaApi.updateSettings(patch));
  };
  const t = (k) => save({ [k]: !s[k] });
  const saveOpenAi = async () => {
    const patch = {
      openaiModel: s.openaiModel,
      openaiInstructions: s.openaiInstructions,
    };
    if (openaiKey.trim()) patch.openaiApiKey = openaiKey.trim();
    const [nextSettings] = await Promise.all([
      window.WaApi.updateSettings(patch),
      window.WaApi.updateOpenaiContext(openaiContext),
    ]);
    setS(nextSettings);
    setOpenaiKey("");
    setSaved("OpenAI settings saved");
    setTimeout(() => setSaved(""), 2500);
  };

  return (
    <div className="page route-anim" style={{ maxWidth: 820 }}>
      {/* Safety guardrails — the important block */}
      <div className="card set-card guard-card">
        <div className="set-card-head">
          <span className="set-head-ic amber"><Icons.shield size={18} /></span>
          <div><h2>Account-safety guardrails</h2><p className="muted">Baileys uses Linked Devices on a normal account — WhatsApp can ban for spammy patterns. These are on by default.</p></div>
        </div>
        <Row title="Dedicated number" desc="Confirm this isn't a primary personal line.">
          <span className={"toggle" + (s.dedicatedNumber ? " on" : "")} onClick={() => t("dedicatedNumber")} style={{ pointerEvents: "auto" }}></span>
        </Row>
        <Row title="Throttle sends" desc="Randomized 3–10s delay between messages.">
          <span className={"toggle" + (s.throttleEnabled ? " on" : "")} onClick={() => t("throttleEnabled")}></span>
        </Row>
        <Row title="Opt-in only" desc="Only auto-message chats that expect it. No cold blasts.">
          <span className={"toggle" + (s.optInOnly ? " on" : "")} onClick={() => t("optInOnly")}></span>
        </Row>
        <Row title="Hourly send cap" desc="Hard ceiling on automated sends per hour.">
          <div className="stepper"><button onClick={() => save({ hourlyCap: Math.max(10, s.hourlyCap - 10) })}>−</button><span className="mono">{s.hourlyCap}</span><button onClick={() => save({ hourlyCap: s.hourlyCap + 10 })}>+</button></div>
        </Row>
        <Row title="Daily send cap" desc="Total automated + manual sends per day.">
          <div className="stepper"><button onClick={() => save({ dailyCap: Math.max(50, s.dailyCap - 50) })}>−</button><span className="mono">{s.dailyCap}</span><button onClick={() => save({ dailyCap: s.dailyCap + 50 })}>+</button></div>
        </Row>
        <Row title="Back off on errors" desc="Pause and retry with backoff when sends fail.">
          <span className={"toggle" + (s.backoffOnErrors ? " on" : "")} onClick={() => t("backoffOnErrors")}></span>
        </Row>
      </div>

      <div className="card set-card">
        <div className="set-card-head">
          <span className="set-head-ic violet"><Icons.message size={18} /></span>
          <div><h2>ChatGPT / OpenAI</h2><p className="muted">Used by automations with the Ask ChatGPT action. The Markdown context is attached to each model request.</p></div>
        </div>
        <Row title="API key" desc={s.hasOpenaiApiKey ? "A key is saved. Paste a new one only when rotating it." : "Paste your OpenAI API key here."}>
          <input className="input mono" type="password" placeholder={s.hasOpenaiApiKey ? "Saved" : "sk-..."} value={openaiKey} onChange={(e) => setOpenaiKey(e.target.value)} />
        </Row>
        <Row title="Model" desc="Default model for ChatGPT automation replies.">
          <input className="input mono" value={s.openaiModel || ""} onChange={(e) => setS((x) => ({ ...x, openaiModel: e.target.value }))} />
        </Row>
        <Row title="Base instructions" desc="Applies to all ChatGPT automation replies.">
          <textarea className="textarea" value={s.openaiInstructions || ""} onChange={(e) => setS((x) => ({ ...x, openaiInstructions: e.target.value }))}></textarea>
        </Row>
        <Row title="Markdown context file" desc="Saved as data/openai-context.md and included with each OpenAI action.">
          <textarea className="textarea mono" style={{ minHeight: 220 }} value={openaiContext} onChange={(e) => setOpenaiContext(e.target.value)}></textarea>
        </Row>
        <Row title="Save OpenAI settings" desc="Stores the key locally in data/settings.json. Keep this file private.">
          <button className="btn primary sm" onClick={saveOpenAi}><Icons.check size={14} /> Save</button>
          {saved && <span className="tag green" style={{ marginLeft: 8 }}>{saved}</span>}
        </Row>
      </div>

      <div className="card set-card">
        <div className="set-card-head">
          <span className="set-head-ic blue"><Icons.link size={18} /></span>
          <div><h2>Connection</h2><p className="muted">Session persistence and reconnect behavior.</p></div>
        </div>
        <Row title="Auto-reconnect" desc="Reconnect on socket close unless logged out.">
          <span className={"toggle" + (s.autoReconnect ? " on" : "")} onClick={() => t("autoReconnect")}></span>
        </Row>
        <Row title="Session storage" desc="File-based auth on the Railway Volume.">
          <code className="mono set-code">{status.authDir || "/data/auth"}</code>
        </Row>
        <Row title="Linked number" desc="The account Wa controls.">
          <button className="btn sm" onClick={() => go("connection")}>Manage <Icons.chevron size={13} /></button>
        </Row>
        <Row title="Log out & clear session" desc="Removes credentials — you'll re-scan to reconnect.">
          <button className="btn danger sm" onClick={async () => { await window.WaApi.logout(); go("connection"); }}><Icons.power size={14} /> Log out</button>
        </Row>
      </div>

      <div className="card set-card">
        <div className="set-card-head">
          <span className="set-head-ic violet"><Icons.globe size={18} /></span>
          <div><h2>API</h2><p className="muted">The dashboard talks to the backend over REST.</p></div>
        </div>
        <Row title="API base URL" desc="Points the dashboard at the backend Railway domain.">
          <code className="mono set-code">{s.apiBaseUrl || window.location.origin}</code>
        </Row>
        <Row title="Webhook (events)" desc="Optional outbound webhook for the activity stream.">
          <span className="tag">{s.webhookUrl || "Not set"}</span>
        </Row>
      </div>
    </div>
  );
}

window.SettingsScreen = SettingsScreen;
