/* ============================================================
   Settings — workspace, sender identity, AI autonomy, sending
   guardrails, deliverability, notifications, lanes.
   ============================================================ */
const SETTINGS_SECTIONS = [
  { id: "identity", label: "Sender identity", icon: "contacts" },
  { id: "ai", label: "AI & autonomy", icon: "sparkles" },
  { id: "sending", label: "Sending", icon: "send" },
  { id: "deliver", label: "Deliverability", icon: "shield" },
  { id: "notify", label: "Notifications", icon: "bell" },
  { id: "lanes", label: "Lanes & tags", icon: "filter" },
  { id: "workspace", label: "Workspace", icon: "settings" },
];

function SetRow({ label, hint, children }) {
  return (
    <div className="set-row">
      <div style={{ minWidth: 0, flex: 1 }}>
        <div className="set-label">{label}</div>
        {hint && <div className="set-hint">{hint}</div>}
      </div>
      <div className="set-control">{children}</div>
    </div>
  );
}
function SetToggle({ on, onChange }) {
  return <button className={"agent-toggle" + (on ? " on" : "")} onClick={() => onChange(!on)}><span className="agent-knob"></span></button>;
}

function Settings({ onClose }) {
  const W = window.WTC;
  const [sec, setSec] = React.useState("identity");
  const [s, setS] = React.useState(() => ({
    name: W.ME.name, replyTo: W.ME.email, title: "Founder, We The Creators",
    signature: "Preston\nWe The Creators",
    credits: ["Rocket SB", "Invisalign SB", "Vita Coco", "Red Bull"],
    autonomy: "Approve every send", tone: "Warm", maxWords: 110, perDay: 8, minFit: 75,
    cap: 30, window: "Business hours", tz: "PT", skipWeekend: true,
    spamAlert: 15, bounceAlert: 3, autoPause: true, dnsCheck: true,
    notifyReply: true, notifyRoundup: true, notifyDeliver: true, quiet: false,
    accent: "#6CACE4", density: "regular",
  }));
  const set = (k, v) => setS((x) => ({ ...x, [k]: v }));
  const toggleCredit = (c) => setS((x) => ({ ...x, credits: x.credits.includes(c) ? x.credits.filter((y) => y !== c) : [...x.credits, c] }));
  const [saved, setSaved] = React.useState(false);
  const save = () => { setSaved(true); setTimeout(() => { setSaved(false); onClose(); }, 700); };

  const LM = W.LANE_META;

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal settings-modal" onClick={(e) => e.stopPropagation()}>
        <div className="settings-side">
          <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "4px 8px 14px" }}>
            <Icon name="settings" size={17} style={{ color: "var(--accent)" }} />
            <span style={{ fontSize: 15, fontWeight: 720 }}>Settings</span>
          </div>
          {SETTINGS_SECTIONS.map((x) => (
            <button key={x.id} className="set-nav" data-active={sec === x.id || undefined} onClick={() => setSec(x.id)}>
              <Icon name={x.icon} size={16} /> {x.label}
            </button>
          ))}
          <div style={{ flex: 1 }}></div>
          <button className="set-nav" style={{ color: "var(--text-3)" }}><Icon name="logout" size={16} /> Sign out</button>
        </div>

        <div className="settings-main">
          <button className="btn btn--ghost btn--icon settings-x" onClick={onClose}><Icon name="x" size={18} /></button>

          {sec === "identity" && (
            <Section title="Sender identity" sub="Who outreach comes from and the voice Claude writes in.">
              <SetRow label="Full name"><input className="input" value={s.name} onChange={(e) => set("name", e.target.value)} /></SetRow>
              <SetRow label="Title"><input className="input" value={s.title} onChange={(e) => set("title", e.target.value)} /></SetRow>
              <SetRow label="Reply-to address" hint="Replies route back to this inbox."><input className="input num" value={s.replyTo} onChange={(e) => set("replyTo", e.target.value)} /></SetRow>
              <SetRow label="Signature"><textarea className="seq-template" style={{ minHeight: 64 }} value={s.signature} onChange={(e) => set("signature", e.target.value)} /></SetRow>
              <SetRow label="Marquee credits" hint="Claude weaves these into outreach as proof.">
                <div className="facet-chips" style={{ justifyContent: "flex-end" }}>{["Rocket SB", "Invisalign SB", "Vita Coco", "Red Bull"].map((c) => (
                  <button key={c} className="facet-chip" data-on={s.credits.includes(c) || undefined} onClick={() => toggleCredit(c)}>{c}</button>
                ))}</div>
              </SetRow>
            </Section>
          )}

          {sec === "ai" && (
            <Section title="AI & autonomy" sub="How much Claude does on its own before you step in.">
              <SetRow label="Autonomy level" hint="The master control for every agent.">
                <Segmented value={s.autonomy} onChange={(v) => set("autonomy", v)} options={["Approve every send", "Auto-send follow-ups", "Full autopilot"]} />
              </SetRow>
              <SetRow label="Default draft tone"><Segmented value={s.tone} onChange={(v) => set("tone", v)} options={["Warm", "Direct", "Punchy"]} /></SetRow>
              <SetSlider label="Max draft length" hint="words" value={s.maxWords} min={60} max={180} onChange={(v) => set("maxWords", v)} />
              <SetSlider label="New prospects / day" value={s.perDay} min={1} max={20} onChange={(v) => set("perDay", v)} />
              <SetSlider label="Minimum fit score" value={s.minFit} min={50} max={95} onChange={(v) => set("minFit", v)} />
            </Section>
          )}

          {sec === "sending" && (
            <Section title="Sending" sub="Pace and timing across all outbound inboxes.">
              <SetSlider label="Daily send cap" hint="per inbox" value={s.cap} min={5} max={100} onChange={(v) => set("cap", v)} />
              <SetRow label="Send window"><Segmented value={s.window} onChange={(v) => set("window", v)} options={["Mornings", "Business hours", "Anytime"]} /></SetRow>
              <SetRow label="Timezone"><Segmented value={s.tz} onChange={(v) => set("tz", v)} options={["PT", "MT", "CT", "ET"]} /></SetRow>
              <SetRow label="Skip weekends" hint="Pause sends Sat & Sun."><SetToggle on={s.skipWeekend} onChange={(v) => set("skipWeekend", v)} /></SetRow>
            </Section>
          )}

          {sec === "deliver" && (
            <Section title="Deliverability" sub="Guardrails that protect your domains.">
              <SetSlider label="Spam-rate alert" hint="%" value={s.spamAlert} min={1} max={30} onChange={(v) => set("spamAlert", v)} />
              <SetSlider label="Bounce alert" hint="%" value={s.bounceAlert} min={1} max={10} onChange={(v) => set("bounceAlert", v)} />
              <SetRow label="Auto-pause over threshold" hint="Stop an inbox the moment it crosses a limit."><SetToggle on={s.autoPause} onChange={(v) => set("autoPause", v)} /></SetRow>
              <SetRow label="Daily SPF / DKIM / DMARC checks"><SetToggle on={s.dnsCheck} onChange={(v) => set("dnsCheck", v)} /></SetRow>
              <SetRow label="Manage inboxes" hint="Connect or warm up sending domains.">
                <button className="btn btn--sm" onClick={onClose}><Icon name="mail" size={14} /> Open on Stats</button>
              </SetRow>
            </Section>
          )}

          {sec === "notify" && (
            <Section title="Notifications" sub="What pings you, and when.">
              <SetRow label="Hot reply" hint="When a target replies with interest."><SetToggle on={s.notifyReply} onChange={(v) => set("notifyReply", v)} /></SetRow>
              <SetRow label="Daily round-up" hint="Morning summary of what's waiting."><SetToggle on={s.notifyRoundup} onChange={(v) => set("notifyRoundup", v)} /></SetRow>
              <SetRow label="Deliverability alerts" hint="Spam / bounce / DNS warnings."><SetToggle on={s.notifyDeliver} onChange={(v) => set("notifyDeliver", v)} /></SetRow>
              <SetRow label="Quiet hours" hint="Mute outside your send window."><SetToggle on={s.quiet} onChange={(v) => set("quiet", v)} /></SetRow>
            </Section>
          )}

          {sec === "lanes" && (
            <Section title="Lanes & tags" sub="The four target types and their colors.">
              {["brand", "agency", "event", "travel"].map((l) => (
                <div key={l} className="lane-set-row">
                  <span className="chip-dot" style={{ background: `var(--lane-${l})`, width: 12, height: 12 }}></span>
                  <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1 }}>{LM[l].label}</span>
                  <span className="num" style={{ fontSize: 12, color: "var(--text-3)" }}>{W.targets.filter((t) => t.lane === l).length} targets</span>
                  <span className="num" style={{ fontSize: 12, color: "var(--text-3)" }}>{W.sequences.filter((sq) => sq.lane === l).length} flows</span>
                </div>
              ))}
              <div className="insp-hint" style={{ marginTop: 10 }}>Lanes drive the type chips, folder filters, and which follow-up flow a tagged contact enters.</div>
            </Section>
          )}

          {sec === "workspace" && (
            <Section title="Workspace" sub="Look and feel.">
              <SetRow label="Accent color">
                <div style={{ display: "flex", gap: 8 }}>{["#6CACE4", "#7FB98C", "#C9A06B", "#B69BE8"].map((c) => (
                  <button key={c} onClick={() => { set("accent", c); document.documentElement.style.setProperty("--accent", c); }}
                    style={{ width: 26, height: 26, borderRadius: 7, background: c, border: s.accent === c ? "2px solid #fff" : "2px solid transparent", cursor: "pointer" }}></button>
                ))}</div>
              </SetRow>
              <SetRow label="Density"><Segmented value={s.density === "compact" ? "Compact" : "Regular"} onChange={(v) => set("density", v === "Compact" ? "compact" : "regular")} options={["Regular", "Compact"]} /></SetRow>
              <SetRow label="Export data" hint="Download targets, contacts & activity as CSV."><button className="btn btn--sm"><Icon name="upload" size={14} /> Export</button></SetRow>
            </Section>
          )}

          <div className="settings-foot">
            <button className="btn" onClick={onClose}>Cancel</button>
            <button className="btn btn--primary" onClick={save}><Icon name={saved ? "check" : "check"} size={15} /> {saved ? "Saved" : "Save changes"}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function Section({ title, sub, children }) {
  return (
    <div className="settings-section">
      <div className="settings-section-head">
        <h2 style={{ fontSize: 17, fontWeight: 700, margin: 0 }}>{title}</h2>
        <p style={{ fontSize: 12.5, color: "var(--text-3)", margin: "3px 0 0" }}>{sub}</p>
      </div>
      {children}
    </div>
  );
}
function SetSlider({ label, hint, value, min, max, onChange }) {
  return (
    <div className="set-row">
      <div style={{ minWidth: 0, flex: 1 }}><div className="set-label">{label}</div></div>
      <div className="set-control" style={{ display: "flex", alignItems: "center", gap: 12, width: 220 }}>
        <input type="range" className="ag-range" min={min} max={max} value={value} onChange={(e) => onChange(+e.target.value)} />
        <span className="num" style={{ fontSize: 13, fontWeight: 700, color: "var(--accent)", minWidth: 44, textAlign: "right" }}>{value}{hint ? " " + hint : ""}</span>
      </div>
    </div>
  );
}
Object.assign(window, { Settings });
