// Atlas · Settings modal
const { useState: useStgState, useEffect: useStgEffect } = React;

const TABS = ["Profile", "Appearance", "Preferences", "Account"];

function SettingsModal({ user, onClose, onSave, theme, setTheme }) {
  const [tab, setTab] = useStgState("Profile");
  const [saving, setSaving] = useStgState(false);
  const [saved, setSaved] = useStgState(false);

  const profile = user?.profile || {};

  const [form, setForm] = useStgState({
    name: user?.name || "",
    title: profile.title || "",
    company: profile.company || "",
    department: profile.department || "",
    companySize: profile.companySize || "",
    useCase: profile.useCase || "",
    defaultReportType: profile.defaultReportType || "tech",
    defaultFormat: profile.defaultFormat || "pdf",
    defaultAudience: profile.defaultAudience || "Internal R&D / science team",
    emailNotifications: profile.emailNotifications !== false,
    digestFrequency: profile.digestFrequency || "weekly",
  });

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSave = async () => {
    setSaving(true);
    try {
      await fetch("/api/profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
      onSave && onSave(form);
    } catch (e) {
      alert("Could not save: " + e.message);
    } finally {
      setSaving(false);
    }
  };

  // Close on Escape
  useStgEffect(() => {
    const handler = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []);

  const COMPANY_SIZES = ["1–10", "11–50", "51–200", "201–1,000", "1,000+"];
  const USE_CASES = ["Academic / university research", "Biotech / pharma R&D", "Corporate strategy & BD", "Investment / VC due diligence", "Market intelligence", "Consulting", "Other"];

  return (
    <div className="modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal">
        <div className="modal-header">
          <h2>Settings</h2>
          <button className="modal-close" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="modal-tabs">
          {TABS.map((t) => (
            <button key={t} className={`modal-tab ${tab === t ? "active" : ""}`} onClick={() => setTab(t)}>{t}</button>
          ))}
        </div>

        <div className="modal-body">

          {/* ── Profile ── */}
          {tab === "Profile" && (
            <>
              <div className="setting-section-label">Personal information</div>

              <div className="setting-row">
                <div><div className="lbl">Full name</div><div className="sub">Shown in reports and the workspace.</div></div>
                <input className="select" style={{ width: 200, fontSize: 13 }} value={form.name} onChange={(e) => set("name", e.target.value)} />
              </div>

              <div className="setting-row">
                <div><div className="lbl">Job title</div></div>
                <input className="select" style={{ width: 200, fontSize: 13 }} value={form.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. VP of R&D" />
              </div>

              <div className="setting-row">
                <div><div className="lbl">Company</div></div>
                <input className="select" style={{ width: 200, fontSize: 13 }} value={form.company} onChange={(e) => set("company", e.target.value)} placeholder="e.g. Acme Bio" />
              </div>

              <div className="setting-row">
                <div><div className="lbl">Department</div></div>
                <input className="select" style={{ width: 200, fontSize: 13 }} value={form.department} onChange={(e) => set("department", e.target.value)} placeholder="e.g. Business Development" />
              </div>

              <div className="setting-row">
                <div><div className="lbl">Company size</div></div>
                <select className="select" style={{ width: 200, fontSize: 13 }} value={form.companySize} onChange={(e) => set("companySize", e.target.value)}>
                  <option value="">—</option>
                  {COMPANY_SIZES.map((s) => <option key={s} value={s}>{s} employees</option>)}
                </select>
              </div>

              <div className="setting-row">
                <div><div className="lbl">Primary use case</div></div>
                <select className="select" style={{ width: 200, fontSize: 13 }} value={form.useCase} onChange={(e) => set("useCase", e.target.value)}>
                  <option value="">—</option>
                  {USE_CASES.map((u) => <option key={u} value={u}>{u}</option>)}
                </select>
              </div>

              <div className="setting-section-label" style={{ marginTop: 24 }}>Login</div>
              <div className="setting-row">
                <div><div className="lbl">Email</div><div className="sub">{user?.email}</div></div>
                <span style={{ fontSize: 11, fontFamily: "var(--mono)", color: "var(--ink-4)", background: "var(--bg-2)", padding: "3px 8px", borderRadius: 4 }}>Google</span>
              </div>
            </>
          )}

          {/* ── Appearance ── */}
          {tab === "Appearance" && (
            <>
              <div className="setting-section-label">Theme</div>
              <div className="setting-row">
                <div>
                  <div className="lbl">Color mode</div>
                  <div className="sub">Choose how Atlas looks for you.</div>
                </div>
                <div className="theme-pills">
                  {["light", "dark"].map((t) => (
                    <button
                      key={t}
                      className={`theme-pill ${theme === t ? "active" : ""}`}
                      onClick={() => setTheme(t)}
                      style={{ textTransform: "capitalize" }}
                    >{t}</button>
                  ))}
                </div>
              </div>

              <div className="setting-section-label" style={{ marginTop: 24 }}>Preview</div>
              <div style={{
                borderRadius: "var(--radius-lg)", border: "1px solid var(--line)",
                overflow: "hidden", background: "var(--bg-2)",
              }}>
                <div style={{ background: "var(--bg)", borderBottom: "1px solid var(--line)", padding: "10px 16px", display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{ width: 16, height: 16, borderRadius: "50%", background: "var(--ink)" }} />
                  <div style={{ fontFamily: "var(--serif)", fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>Atlas</div>
                  <div style={{ flex: 1 }} />
                  <div style={{ width: 60, height: 8, borderRadius: 4, background: "var(--line-2)" }} />
                </div>
                <div style={{ padding: 16 }}>
                  <div style={{ width: "60%", height: 10, borderRadius: 4, background: "var(--line)", marginBottom: 8 }} />
                  <div style={{ width: "40%", height: 8, borderRadius: 4, background: "var(--line-2)" }} />
                </div>
              </div>
            </>
          )}

          {/* ── Preferences ── */}
          {tab === "Preferences" && (
            <>
              <div className="setting-section-label" style={{ marginTop: 24 }}>Notifications</div>

              <div className="setting-row">
                <div><div className="lbl">Email notifications</div><div className="sub">Get notified when a report completes.</div></div>
                <button className={`toggle ${form.emailNotifications ? "on" : ""}`} onClick={() => set("emailNotifications", !form.emailNotifications)} />
              </div>

              <div className="setting-row">
                <div>
                  <div className="lbl">Report digest</div>
                  <div className="sub">Receive a summary of your recent reports by email.</div>
                </div>
                <select
                  className="select"
                  style={{ width: 140, fontSize: 13 }}
                  value={form.digestFrequency}
                  onChange={(e) => set("digestFrequency", e.target.value)}
                >
                  <option value="off">Off</option>
                  <option value="weekly">Weekly</option>
                  <option value="biweekly">Bi-weekly</option>
                  <option value="monthly">Monthly</option>
                </select>
              </div>
            </>
          )}

          {/* ── Account ── */}
          {tab === "Account" && (
            <>
              <div className="setting-section-label">Plan</div>
              <div className="setting-row">
                <div><div className="lbl">Current plan</div><div className="sub">Atlas Enterprise</div></div>
                <span style={{ fontSize: 11, fontFamily: "var(--mono)", color: "var(--success)", background: "var(--success-tint)", padding: "3px 9px", borderRadius: 20 }}>Active</span>
              </div>
              <div className="setting-row">
                <div><div className="lbl">Reports this month</div><div className="sub">Usage resets on the 1st.</div></div>
                <span style={{ fontSize: 13, fontFamily: "var(--mono)", color: "var(--ink-2)" }}>—</span>
              </div>

              <div className="setting-section-label" style={{ marginTop: 24 }}>Billing</div>
              <div className="setting-row">
                <div><div className="lbl">Billing contact</div><div className="sub">Managed by your Atlas account team.</div></div>
                <a href="mailto:ramy@notedsource.com" style={{ fontSize: 12, color: "var(--ink-3)", textDecoration: "none" }}>Contact us</a>
              </div>

              <div className="setting-section-label" style={{ marginTop: 24 }}>Danger zone</div>
              <div className="setting-row">
                <div><div className="lbl">Sign out everywhere</div><div className="sub">Clears all active sessions.</div></div>
                <a href="/auth/logout" className="btn ghost sm" style={{ color: "var(--rose)", textDecoration: "none" }}>Sign out</a>
              </div>
            </>
          )}

        </div>

        <div className="modal-footer">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={saving} onClick={handleSave}>
            {saved ? "Saved ✓" : saving ? "Saving…" : "Save changes"}
          </button>
        </div>
      </div>
    </div>
  );
}

window.SettingsModal = SettingsModal;
