// mailroom-settings.jsx — Settings / Connections (BYO keys). Provider connect
// grid, Smartlead webhook card (loud secret state), booking link, connect/manage
// drawers, set-secret + add-link modals. Exports: ViewSettings.

const PROVIDERS = [
  { id: "smartlead", name: "Smartlead", role: "Sequencer", mark: "S", color: "#3a6df0",
    desc: "Owns sending, sequences & reply sync", state: "connected", ver: "verified 4m ago" },
  { id: "maildoso", name: "Maildoso", role: "Provisioner", mark: "M", color: "#1f9d6b",
    desc: "Buys domains, provisions inboxes, warmup", state: "connected", ver: "verified 1h ago" },
  { id: "namecheap", name: "Namecheap", role: "Registrar", mark: "N", color: "#d4541f",
    desc: "Registers domains via API", state: "connected", ver: "verified 2h ago" },
  { id: "airscale", name: "Airscale", role: "Lead source", mark: "A", color: "#7a5ae0",
    desc: "Pushes verified leads via webhook", state: "disconnected", ver: "never connected" },
  { id: "lithic", name: "Lithic", role: "Virtual card", mark: "L", color: "#0f9d8f",
    desc: "Funds domain purchases — spend control", state: "attention", ver: "balance low · $4.20" },
  { id: "openrouter", name: "OpenRouter", role: "AI", mark: "O", color: "#5b6470",
    desc: "Classifies replies, drafts responses", state: "connected", ver: "verified 12m ago" },
  { id: "telegram", name: "Telegram", role: "Notifications", mark: "T", color: "#2f9fd6",
    desc: "One-tap reply approvals on your phone", state: "connected", ver: "verified 8m ago" },
];
const PSTATE = {
  connected: { tone: "good", label: "connected", icon: "check" },
  disconnected: { tone: "bad", label: "not connected", icon: "x" },
  attention: { tone: "warn", label: "needs attention", icon: "alert" },
};

function ViewSettings() {
  const t = useT();
  const [copied, setCopied] = React.useState(false);
  const [secretSet, setSecretSet] = React.useState(false);
  const [bookingSet, setBookingSet] = React.useState(false);
  const [tgOn, setTgOn] = React.useState(true);
  const [provs, setProvs] = React.useState(PROVIDERS);
  const [draw, setDraw] = React.useState(null);     // provider object
  const [secretModal, setSecretModal] = React.useState(false);
  const [linkModal, setLinkModal] = React.useState(false);
  const webhook = "https://api.igtre.studio/v1/cold/smartlead/wh_8fa2c19b";

  const copy = () => { setCopied(true); navigator.clipboard && navigator.clipboard.writeText(webhook).catch(() => {}); mrToast("Webhook URL copied", { icon: "copy" }); setTimeout(() => setCopied(false), 1400); };
  const counts = {
    connected: provs.filter((p) => p.state === "connected").length,
    attention: provs.filter((p) => p.state === "attention").length,
    off: provs.filter((p) => p.state === "disconnected").length,
  };
  const connectProvider = (id) => {
    setProvs((ps) => ps.map((p) => p.id === id ? { ...p, state: "connected", ver: "verified just now" } : p));
    setDraw(null);
    mrToast("Connected — verified just now", { tone: "good", icon: "plug" });
  };

  return (
    <>
      <PageHeader title="Settings · Connections" sub="Bring your own keys — Mailroom never stores credentials in plaintext" />

      <div style={{ flex: 1, overflowY: "auto", padding: t.pad, display: "flex", flexDirection: "column", gap: t.pad }}>
        {/* webhook */}
        <Card style={{ borderColor: secretSet ? t.border : t.markerBorder }}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 13 }}>
            <div style={{ width: 38, height: 38, borderRadius: t.radiusSm, background: t.console, color: t.consoleText,
              display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
              <Icon name="link" size={18} color={t.consoleText} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                <span style={{ fontFamily: t.head, fontSize: 15, fontWeight: 700, color: t.text }}>Smartlead webhook</span>
                <Chip tone="neutral" mono>per-account</Chip>
              </div>
              <div style={{ fontSize: 12.5, color: t.textMuted, marginTop: 3 }}>Paste this into Smartlead → Settings → Webhooks to sync replies in real time.</div>

              <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, padding: "0 4px 0 12px", height: t.ctrlH,
                border: `1px solid ${t.borderStrong}`, borderRadius: t.radiusSm, background: t.dark ? t.sunken : t.bg }}>
                <Mono style={{ fontSize: 12.5, color: t.textSec, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{webhook}</Mono>
                <Btn kind={copied ? "accentSoft" : "soft"} size="sm" icon={copied ? "check" : "copy"} onClick={copy}>{copied ? "Copied" : "Copy"}</Btn>
              </div>

              {secretSet ? (
                <div style={{ display: "flex", alignItems: "center", gap: 11, marginTop: 12, padding: "11px 14px", borderRadius: t.radiusSm,
                  background: t.goodTint, border: `1px solid ${hexA(t.good, 0.3)}` }}>
                  <Icon name="checkCircle" size={18} color={t.good} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>Signing secret set</div>
                    <div style={{ fontSize: 12, color: t.textMuted, marginTop: 1 }}>Inbound replies are verified. <Mono>wh_secret · ••••3f9a</Mono></div>
                  </div>
                  <Btn kind="soft" size="sm" icon="refresh" onClick={() => setSecretModal(true)}>Rotate</Btn>
                </div>
              ) : (
                <div style={{ display: "flex", alignItems: "center", gap: 11, marginTop: 12, padding: "12px 14px", borderRadius: t.radiusSm,
                  background: t.markerTint, border: `1.5px solid ${t.markerBorder}` }}>
                  <div style={{ width: 28, height: 28, borderRadius: 999, background: t.marker, display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
                    <Icon name="alert" size={16} color="#5c4700" sw={2} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: t.markerInk }}>Signing secret not set</div>
                    <div style={{ fontSize: 12, color: t.textSec, marginTop: 1 }}>Replies won't be trusted until you set the shared secret. <b style={{ color: t.text }}>Required.</b></div>
                  </div>
                  <Btn kind="marker" size="sm" icon="key" onClick={() => setSecretModal(true)}>Set secret</Btn>
                </div>
              )}
            </div>
          </div>
        </Card>

        {/* providers grid */}
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
            <span style={{ fontFamily: t.head, fontSize: 15, fontWeight: 700, color: t.text }}>Connections</span>
            <span style={{ fontSize: 12, color: t.textMuted, fontFamily: t.mono }}>{counts.connected} connected · {counts.attention} attention · {counts.off} off</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: t.gap }}>
            {provs.map((p) => {
              const st = PSTATE[p.state];
              const connected = p.state !== "disconnected";
              return (
                <Card key={p.id} style={{ padding: 0, overflow: "hidden",
                  borderLeft: connected ? `3px solid ${t.accent}` : `1px solid ${t.border}` }}>
                  <div style={{ padding: 16 }}>
                    <div style={{ display: "flex", alignItems: "flex-start", gap: 11 }}>
                      <div style={{ width: 38, height: 38, borderRadius: t.radiusSm, flex: "0 0 auto",
                        background: hexA(p.color, t.dark ? 0.28 : 0.14), border: `1px solid ${hexA(p.color, 0.4)}`,
                        display: "flex", alignItems: "center", justifyContent: "center" }}>
                        <span style={{ fontFamily: t.head, fontWeight: 800, fontSize: 17, color: p.color }}>{p.mark}</span>
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                          <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>{p.name}</span>
                          <Chip tone="neutral" style={{ fontSize: 10 }}>{p.role}</Chip>
                        </div>
                        <div style={{ fontSize: 12, color: t.textMuted, marginTop: 3, lineHeight: 1.4 }}>{p.desc}</div>
                      </div>
                      {connected && <Icon name="checkCircle" size={18} color={st.tone === "good" ? t.good : t.warn} />}
                    </div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 16px", borderTop: `1px solid ${t.border}`,
                    background: t.dark ? t.sunken : t.bg }}>
                    <StatusChip tone={st.tone} dotPulse={false}>{st.label}</StatusChip>
                    <span style={{ fontSize: 11, color: t.textMuted, fontFamily: t.mono, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.ver}</span>
                    <Btn kind={connected ? "soft" : "primary"} size="sm" icon={connected ? "settings" : "plug"} onClick={() => setDraw(p)}>{connected ? "Manage" : "Connect"}</Btn>
                  </div>
                </Card>
              );
            })}
          </div>
        </div>

        {/* operator prefs */}
        <Card>
          <div style={{ fontFamily: t.head, fontSize: 15, fontWeight: 700, color: t.text, marginBottom: 4 }}>Operator preferences</div>
          <SettingLine t={t} title="Booking link" sub="Inserted into POSITIVE / BOOKING reply drafts">
            {bookingSet ? (
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <Chip tone="good" icon="check" mono>cal.com/mohit</Chip>
                <Btn kind="soft" size="sm" icon="pencil" onClick={() => setLinkModal(true)}>Edit</Btn>
              </div>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <Chip tone="warn" icon="alert">not set</Chip>
                <Btn kind="soft" size="sm" icon="calendar" onClick={() => setLinkModal(true)}>Add link</Btn>
              </div>
            )}
          </SettingLine>
          <SettingLine t={t} title="Telegram approvals" sub="Approve & send replies from your phone, one tap each">
            <Toggle on={tgOn} onClick={() => { setTgOn(!tgOn); mrToast(tgOn ? "Telegram approvals off" : "Telegram approvals on", { tone: tgOn ? "warn" : "good", icon: "plug" }); }} />
          </SettingLine>
          <SettingLine t={t} title="Daily spend cap" sub="Hard limit on agent purchases (domains, top-ups)" last>
            <div style={{ display: "flex", alignItems: "center", gap: 8, height: t.ctrlH, border: `1px solid ${t.borderStrong}`,
              borderRadius: t.radiusSm, padding: "0 11px", background: t.raise }}>
              <Mono style={{ fontSize: 13, color: t.textMuted }}>$</Mono>
              <input defaultValue="100.00" style={{ width: 60, border: "none", outline: "none", background: "transparent",
                fontFamily: t.mono, fontSize: 13, fontWeight: 700, color: t.text }} />
            </div>
          </SettingLine>
        </Card>
      </div>

      {/* provider connect / manage drawer */}
      <ProviderDrawer p={draw} onClose={() => setDraw(null)} onConnect={connectProvider} />

      {/* set / rotate secret modal (loud) */}
      <Modal open={secretModal} onClose={() => setSecretModal(false)} loud icon="key" iconTone="marker"
        title={secretSet ? "Rotate signing secret" : "Set signing secret"}
        sub="A shared secret Smartlead signs each webhook with. Mailroom rejects any unsigned reply."
        footer={<>
          <Btn kind="ghost" onClick={() => setSecretModal(false)}>Cancel</Btn>
          <div style={{ flex: 1 }} />
          <Btn kind="primary" icon="check" onClick={() => { setSecretSet(true); setSecretModal(false); mrToast("Signing secret saved — replies now verified", { tone: "good", icon: "shield" }); }}>Save secret</Btn>
        </>}>
        <Field label="Shared secret" value="wh_secret_8fa2c19b3f9a" mono onChange={() => {}} />
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 10 }}>
          <Btn kind="soft" size="sm" icon="refresh" onClick={() => mrToast("New secret generated", { icon: "key" })}>Generate</Btn>
          <span style={{ fontSize: 11.5, color: t.textMuted }}>Paste the same value into Smartlead's webhook config.</span>
        </div>
      </Modal>

      {/* add / edit booking link modal */}
      <Modal open={linkModal} onClose={() => setLinkModal(false)} icon="calendar" title={bookingSet ? "Edit booking link" : "Add booking link"}
        sub="The AI inserts this into POSITIVE and BOOKING reply drafts."
        footer={<>
          <Btn kind="ghost" onClick={() => setLinkModal(false)}>Cancel</Btn>
          <div style={{ flex: 1 }} />
          <Btn kind="primary" icon="check" onClick={() => { setBookingSet(true); setLinkModal(false); mrToast("Booking link saved", { tone: "good", icon: "calendar" }); }}>Save link</Btn>
        </>}>
        <Field label="Booking URL" value="https://cal.com/mohit/15min" mono onChange={() => {}} />
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, padding: "9px 12px", borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
          <Icon name="sparkle" size={14} color={t.accent} />
          <span style={{ fontSize: 12, color: t.textSec }}>Drafts will read “grab a time here: cal.com/mohit/15min”.</span>
        </div>
      </Modal>
    </>
  );
}

function ProviderDrawer({ p, onClose, onConnect }) {
  const t = useT();
  if (!p) return null;
  const connected = p.state !== "disconnected";
  return (
    <Drawer open={!!p} onClose={onClose} width={440}
      title={<span style={{ display: "flex", alignItems: "center", gap: 9 }}>
        <span style={{ width: 26, height: 26, borderRadius: 6, background: hexA(p.color, t.dark ? 0.28 : 0.14), border: `1px solid ${hexA(p.color, 0.4)}`,
          display: "flex", alignItems: "center", justifyContent: "center", fontFamily: t.head, fontWeight: 800, fontSize: 13, color: p.color }}>{p.mark}</span>
        {p.name}</span>}
      sub={`${p.role} · ${p.desc}`}
      footer={connected ? <>
        <Btn kind="danger" icon="x" onClick={() => { onClose(); mrToast(`${p.name} disconnected`, { tone: "warn", icon: "x" }); }}>Disconnect</Btn>
        <div style={{ flex: 1 }} />
        <Btn kind="primary" icon="check" onClick={() => { onClose(); mrToast(`${p.name} settings saved`, { tone: "good", icon: "check" }); }}>Save</Btn>
      </> : <>
        <Btn kind="ghost" onClick={onClose}>Cancel</Btn>
        <div style={{ flex: 1 }} />
        <Btn kind="primary" icon="plug" onClick={() => onConnect(p.id)}>Connect {p.name}</Btn>
      </>}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 18 }}>
        <StatusChip tone={PSTATE[p.state].tone} dotPulse={false}>{PSTATE[p.state].label}</StatusChip>
        <span style={{ fontSize: 12, color: t.textMuted, fontFamily: t.mono }}>{p.ver}</span>
      </div>
      <Field label="API key" value={connected ? "sk_live_••••••••••••4c19" : ""} placeholder="paste your key" mono onChange={() => {}} style={{ marginBottom: 14 }} />
      {p.id === "telegram" && <Field label="Chat ID" value={connected ? "@mohit_mailroom" : ""} placeholder="@your_handle" mono onChange={() => {}} style={{ marginBottom: 14 }} />}
      <div style={{ display: "flex", alignItems: "flex-start", gap: 9, padding: "11px 13px", borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
        <Icon name="shield" size={15} color={t.textMuted} style={{ marginTop: 1 }} />
        <span style={{ fontSize: 12, color: t.textSec, lineHeight: 1.5 }}>Keys are encrypted at rest and never shown again after saving. Used only by your account's agent.</span>
      </div>
    </Drawer>
  );
}

function SettingLine({ t, title, sub, children, last }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "14px 0",
      borderBottom: last ? "none" : `1px solid ${t.border}` }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{ flex: "0 0 auto" }}>{children}</div>
    </div>
  );
}
window.ViewSettings = ViewSettings;
