// Settings drawer — BYOK provider + key, persisted to resumeforge.user_settings.

const { useState: useStateSet, useEffect: useEffectSet } = React;

const PROVIDERS = [
  { key: "claude", name: "Claude Sonnet 4.6", sub: "Anthropic", field: "anthropic_api_key", modelField: "anthropic_model", modelPlaceholder: "claude-sonnet-4-6" },
  { key: "gemini", name: "Gemini 2.5 Pro",    sub: "Google",    field: "gemini_api_key",    modelField: "gemini_model",    modelPlaceholder: "gemini-2.5-pro" },
  { key: "grok",   name: "Grok 4 Fast",       sub: "xAI",       field: "xai_api_key",       modelField: "xai_model",       modelPlaceholder: "grok-4-fast" },
];

function SettingsDrawer({ open, onClose }) {
  const auth = (window.useForgeAuth && window.useForgeAuth()) || { enabled: false, user: null };
  const [provider, setProvider] = useStateSet("claude");
  const [keys, setKeys] = useStateSet({ anthropic_api_key: "", gemini_api_key: "", xai_api_key: "" });
  const [models, setModels] = useStateSet({ anthropic_model: "", gemini_model: "", xai_model: "" });
  const [loading, setLoading] = useStateSet(false);
  const [saving, setSaving] = useStateSet(false);
  const [savedAt, setSavedAt] = useStateSet(null);
  const [err, setErr] = useStateSet(null);

  // Load existing settings on open / on auth change.
  useEffectSet(() => {
    if (!open || !auth.user || !window.ForgeDB?.isEnabled()) return;
    let cancelled = false;
    setLoading(true);
    window.ForgeDB.getSettings()
      .then((row) => {
        if (cancelled || !row) return;
        setProvider(row.provider || "claude");
        setKeys({
          anthropic_api_key: row.anthropic_api_key || "",
          gemini_api_key: row.gemini_api_key || "",
          xai_api_key: row.xai_api_key || "",
        });
        setModels({
          anthropic_model: row.anthropic_model || "",
          gemini_model: row.gemini_model || "",
          xai_model: row.xai_model || "",
        });
      })
      .catch((e) => !cancelled && setErr(e.message))
      .finally(() => !cancelled && setLoading(false));
    return () => { cancelled = true; };
  }, [open, auth.user?.id]);

  const save = async () => {
    setSaving(true); setErr(null);
    try {
      // Empty strings → null so the Edge Function uses its default.
      const cleanModels = Object.fromEntries(
        Object.entries(models).map(([k, v]) => [k, v.trim() ? v.trim() : null])
      );
      await window.ForgeDB.saveSettings({ provider, ...keys, ...cleanModels });
      setSavedAt(Date.now());
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  };

  const activeProvider = PROVIDERS.find((p) => p.key === provider);
  const activeField = activeProvider.field;
  const activeModelField = activeProvider.modelField;

  return (
    <>
      <div
        onClick={onClose}
        style={{
          position: "fixed", inset: 0, background: "rgba(27,24,20,0.18)",
          opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none",
          transition: "opacity 200ms", zIndex: 100,
        }}
      />
      <div
        style={{
          position: "fixed", top: 0, right: 0, bottom: 0, width: 440,
          background: "var(--paper)", borderLeft: "1px solid var(--border)",
          transform: open ? "translateX(0)" : "translateX(100%)",
          transition: "transform 240ms cubic-bezier(.2,.8,.2,1)",
          zIndex: 101, overflowY: "auto",
          boxShadow: "-20px 0 40px -20px rgba(27,24,20,0.2)",
        }}
      >
        <div style={{ padding: "32px 36px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <Eyebrow style={{ marginBottom: 4 }}>Preferences</Eyebrow>
            <div style={{ fontFamily: "Newsreader, serif", fontSize: 26, fontWeight: 400, letterSpacing: "-0.02em", color: "var(--ink)" }}>
              Settings
            </div>
          </div>
          <button
            onClick={onClose}
            style={{ width: 30, height: 30, borderRadius: 6, border: "1px solid var(--border)", background: "transparent", cursor: "pointer", color: "var(--ink)", display: "flex", alignItems: "center", justifyContent: "center" }}
          >
            {Icon.x}
          </button>
        </div>

        <div style={{ padding: "32px 36px" }}>
          {!auth.user && (
            <div
              style={{
                padding: "14px 16px",
                background: "var(--paper-2)",
                border: "1px solid var(--border)",
                borderRadius: 6,
                color: "var(--muted)",
                fontSize: 13,
                lineHeight: 1.5,
                marginBottom: 28,
              }}
            >
              Sign in to save provider + API key. Settings are stored per account.
            </div>
          )}

          {/* AI Provider */}
          <Eyebrow style={{ marginBottom: 12 }}>AI provider</Eyebrow>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 8 }}>
            {PROVIDERS.map((p) => {
              const active = provider === p.key;
              const hasKey = Boolean(keys[p.field]);
              return (
                <button
                  key={p.key}
                  onClick={() => setProvider(p.key)}
                  disabled={!auth.user}
                  style={{
                    textAlign: "left", padding: "14px 16px",
                    background: active ? "var(--paper-2)" : "transparent",
                    border: `1px solid ${active ? "var(--ink)" : "var(--border)"}`,
                    borderRadius: 6,
                    cursor: auth.user ? "pointer" : "not-allowed",
                    opacity: auth.user ? 1 : 0.6,
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                  }}
                >
                  <div>
                    <div style={{ fontFamily: "Inter, sans-serif", fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>
                      {p.name}
                    </div>
                    <div style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                      {p.sub} · {hasKey ? "key saved" : "no key"}
                    </div>
                  </div>
                  <div
                    style={{
                      width: 16, height: 16, borderRadius: 999,
                      border: `1.5px solid ${active ? "var(--ink)" : "var(--border)"}`,
                      background: active ? "var(--ink)" : "transparent",
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}
                  >
                    {active && <div style={{ width: 6, height: 6, background: "var(--paper)", borderRadius: 999 }} />}
                  </div>
                </button>
              );
            })}
          </div>
          <div style={{ fontFamily: "Inter, sans-serif", fontSize: 11, color: "var(--muted)", lineHeight: 1.5, marginBottom: 28 }}>
            Bring your own key. Keys are stored on your account in Supabase and only used to call your chosen provider.
          </div>

          <Rule style={{ marginBottom: 28 }} />

          {/* API key field for the active provider */}
          <Eyebrow style={{ marginBottom: 12 }}>
            API key · {PROVIDERS.find((p) => p.key === provider).sub}
          </Eyebrow>
          <input
            type="password"
            autoComplete="off"
            spellCheck={false}
            disabled={!auth.user || loading}
            value={keys[activeField]}
            onChange={(e) => setKeys((k) => ({ ...k, [activeField]: e.target.value }))}
            placeholder={
              provider === "claude" ? "sk-ant-..." :
              provider === "gemini" ? "AIza..." :
              "xai-..."
            }
            style={{
              width: "100%",
              padding: "12px 14px",
              border: "1px solid var(--border)",
              borderRadius: 6,
              background: "var(--paper-2)",
              color: "var(--ink)",
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 13,
              marginBottom: 12,
            }}
          />
          <Eyebrow style={{ marginTop: 18, marginBottom: 12 }}>Model</Eyebrow>
          <input
            type="text"
            autoComplete="off"
            spellCheck={false}
            disabled={!auth.user || loading}
            value={models[activeModelField]}
            onChange={(e) => setModels((m) => ({ ...m, [activeModelField]: e.target.value }))}
            placeholder={`Default: ${activeProvider.modelPlaceholder}`}
            style={{
              width: "100%",
              padding: "12px 14px",
              border: "1px solid var(--border)",
              borderRadius: 6,
              background: "var(--paper-2)",
              color: "var(--ink)",
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 13,
              marginBottom: 6,
            }}
          />
          <div style={{ fontFamily: "Inter, sans-serif", fontSize: 11, color: "var(--muted)", lineHeight: 1.5, marginBottom: 14 }}>
            {provider === "grok" && <>e.g. <code>grok-4</code>, <code>grok-4-fast</code>, <code>grok-3</code>, <code>grok-3-mini</code>, <code>grok-code-fast-1</code>. Leave blank for default.</>}
            {provider === "claude" && <>e.g. <code>claude-opus-4-7</code>, <code>claude-sonnet-4-6</code>, <code>claude-haiku-4-5-20251001</code>. Leave blank for default.</>}
            {provider === "gemini" && <>e.g. <code>gemini-2.5-pro</code>, <code>gemini-2.5-flash</code>. Leave blank for default.</>}
          </div>

          <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 8 }}>
            <button
              onClick={save}
              disabled={!auth.user || saving}
              style={{
                background: "var(--accent)", color: "#14180A", border: "none",
                padding: "9px 16px", borderRadius: 999,
                fontSize: 13, fontWeight: 500,
                cursor: !auth.user || saving ? "default" : "pointer",
                opacity: !auth.user || saving ? 0.6 : 1,
              }}
            >
              {saving ? "Saving…" : "Save"}
            </button>
            {savedAt && !saving && (
              <span style={{ fontSize: 12, color: "var(--muted)" }}>Saved.</span>
            )}
            {err && (
              <span style={{ fontSize: 12, color: "#E08A6B" }}>{err}</span>
            )}
          </div>
          <div style={{ fontFamily: "Inter, sans-serif", fontSize: 11, color: "var(--muted)", lineHeight: 1.5 }}>
            Get a key:{" "}
            {provider === "claude" && <a href="https://console.anthropic.com/settings/keys" target="_blank" rel="noreferrer" style={{ color: "var(--accent)" }}>console.anthropic.com</a>}
            {provider === "gemini" && <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noreferrer" style={{ color: "var(--accent)" }}>aistudio.google.com</a>}
            {provider === "grok"   && <a href="https://console.x.ai" target="_blank" rel="noreferrer" style={{ color: "var(--accent)" }}>console.x.ai</a>}
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { SettingsDrawer });
