/* ============================================================
   settings.jsx — accent presets, helpers, Settings modal
   ============================================================ */

function hexToRgba(hex, a) {
  const h = hex.replace("#", "");
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  return `rgba(${r},${g},${b},${a})`;
}
function darken(hex, amt) {
  const h = hex.replace("#", "");
  const f = (i) => clamp(Math.round(parseInt(h.slice(i, i + 2), 16) * (1 - amt)), 0, 255);
  return `#${[0, 2, 4].map(i => f(i).toString(16).padStart(2, "0")).join("")}`;
}

// soft, Apple-like accent presets. "coral" = the theme default (per-mode in CSS)
const ACCENTS = [
  { key: "coral",  name: "Koraal",   hex: "#E27A5E" },
  { key: "ocean",  name: "Oceaan",   hex: "#5B93E0" },
  { key: "sage",   name: "Salie",    hex: "#5FA88A" },
  { key: "lilac",  name: "Lavendel", hex: "#9B7FD0" },
  { key: "rose",   name: "Roze",     hex: "#D389A0" },
  { key: "slate",  name: "Grafiet",  hex: "#7E8A99" },
];

function applyAccent(key) {
  const root = document.documentElement;
  const props = ["--accent", "--accent-deep", "--accent-weak", "--accent-soft"];
  if (!key || key === "coral") { props.forEach(p => root.style.removeProperty(p)); return; }
  const a = ACCENTS.find(x => x.key === key);
  if (!a) return;
  root.style.setProperty("--accent", a.hex);
  root.style.setProperty("--accent-deep", darken(a.hex, 0.14));
  root.style.setProperty("--accent-weak", hexToRgba(a.hex, 0.14));
  root.style.setProperty("--accent-soft", hexToRgba(a.hex, 0.07));
}

function IntegrationsSection() {
  const [tick, setTick] = useState(0);
  const [busy, setBusy] = useState(false);
  const { data } = useAsync(() => getCalendarStatus(), [tick]);
  const connected = data && data.connected;

  const connect = async () => { setBusy(true); try { await connectGoogleCalendar(); setTick(t => t + 1); } finally { setBusy(false); } };
  const disconnect = async () => {
    if (!window.confirm("Google Agenda ontkoppelen? Je afspraken verdwijnen uit het dashboard.")) return;
    setBusy(true); try { await disconnectGoogleCalendar(); setTick(t => t + 1); } finally { setBusy(false); }
  };
  const toggle = async (id, en) => { await setCalendarEnabled(id, en); setTick(t => t + 1); };

  return (
    <div className="set-group">
      <div className="set-group-lbl">Integraties</div>
      <div className="set-card">
        <div className="set-row">
          <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
            <div style={{ width: 34, height: 34, borderRadius: 9, background: "var(--surface-3)", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <GoogleGlyph size={18} />
            </div>
            <div style={{ minWidth: 0 }}>
              <div className="set-row-label">Google Agenda</div>
              <div className="set-row-sub" style={{ display: "flex", alignItems: "center", gap: 5 }}>
                {connected
                  ? <><span style={{ width: 7, height: 7, borderRadius: 99, background: "var(--good)" }} />{data.email}</>
                  : "Niet gekoppeld"}
              </div>
            </div>
          </div>
          {connected
            ? <button className="btn btn-sm" disabled={busy} onClick={disconnect} style={{ background: "rgba(210,122,107,0.14)", color: "var(--bad)" }}>Ontkoppelen</button>
            : <button className="g-btn g-btn-sm" disabled={busy} onClick={connect}>{busy ? <><span className="spinner" /> …</> : <><GoogleGlyph size={15} /> Koppelen</>}</button>}
        </div>
        {connected && (
          <div className="set-row" style={{ alignItems: "flex-start" }}>
            <div>
              <div className="set-row-label">Zichtbare agenda's</div>
              <div className="set-row-sub">Kies welke agenda's je in het dashboard ziet</div>
            </div>
            <div className="cal-toggle-grid">
              {data.calendars.map(c => (
                <button key={c.id} className={"cal-leg" + (c.enabled ? "" : " off")} onClick={() => toggle(c.id, !c.enabled)}>
                  <span className="cal-leg-dot" style={{ background: c.enabled ? c.color : "var(--text-3)" }} />{c.name}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function SettingsModal({ open, onClose, settings, setSettings, theme, setTheme }) {
  if (!open) return null;
  const set = (k, v) => setSettings(s => ({ ...s, [k]: v }));

  const resetAll = () => {
    if (!window.confirm("Weet je het zeker? Dit wist al je gegevens (gewoontes, taken, mood, water, doelen…) en herstelt de standaardwaarden.")) return;
    Object.keys(localStorage).filter(k => k.startsWith("roan_")).forEach(k => localStorage.removeItem(k));
    location.reload();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div className="modal-title">Instellingen</div>
          <button className="round-btn" onClick={onClose}><Icon name="plus" style={{ transform: "rotate(45deg)" }} /></button>
        </div>
        <div className="modal-body">

          <div className="set-group">
            <div className="set-group-lbl">Profiel</div>
            <div className="set-card">
              <div className="set-row">
                <div>
                  <div className="set-row-label">Naam</div>
                  <div className="set-row-sub">Gebruikt in je begroeting</div>
                </div>
                <input className="set-input" value={settings.name}
                  onChange={e => set("name", e.target.value.slice(0, 24))} placeholder="Je naam" />
              </div>
            </div>
          </div>

          <div className="set-group">
            <div className="set-group-lbl">Weergave</div>
            <div className="set-card">
              <div className="set-row">
                <div>
                  <div className="set-row-label">Thema</div>
                  <div className="set-row-sub">Licht of donker</div>
                </div>
                <div className="seg">
                  <button className={theme === "light" ? "on" : ""} onClick={() => setTheme("light")}>Licht</button>
                  <button className={theme === "dark" ? "on" : ""} onClick={() => setTheme("dark")}>Donker</button>
                </div>
              </div>
              <div className="set-row">
                <div>
                  <div className="set-row-label">Accentkleur</div>
                  <div className="set-row-sub">{ACCENTS.find(a => a.key === (settings.accent || "coral")).name}</div>
                </div>
                <div className="swatches">
                  {ACCENTS.map(a => (
                    <button key={a.key} className={"swatch" + ((settings.accent || "coral") === a.key ? " on" : "")}
                      style={{ background: a.hex, color: a.hex }} title={a.name}
                      onClick={() => set("accent", a.key)} />
                  ))}
                </div>
              </div>
            </div>
          </div>

          <IntegrationsSection />

          <div className="set-group">
            <div className="set-group-lbl">Doelen</div>
            <div className="set-card">
              <div className="set-row">
                <div>
                  <div className="set-row-label">Waterdoel</div>
                  <div className="set-row-sub">Glazen per dag</div>
                </div>
                <div className="stepper">
                  <button onClick={() => set("waterGoal", clamp((settings.waterGoal || 8) - 1, 1, 16))}><Icon name="minus" /></button>
                  <span className="val">{settings.waterGoal || 8}</span>
                  <button onClick={() => set("waterGoal", clamp((settings.waterGoal || 8) + 1, 1, 16))}><Icon name="plus" /></button>
                </div>
              </div>
              <div className="set-row">
                <div>
                  <div className="set-row-label">Weekdoel beweging</div>
                  <div className="set-row-sub">Minuten per week</div>
                </div>
                <div className="stepper">
                  <button onClick={() => set("sportGoal", clamp((settings.sportGoal || 250) - 30, 30, 900))}><Icon name="minus" /></button>
                  <span className="val">{settings.sportGoal || 250}</span>
                  <button onClick={() => set("sportGoal", clamp((settings.sportGoal || 250) + 30, 30, 900))}><Icon name="plus" /></button>
                </div>
              </div>
            </div>
          </div>

          <div className="set-group">
            <div className="set-group-lbl">Gegevens</div>
            <div className="set-card">
              <div className="set-row">
                <div>
                  <div className="set-row-label">Alles wissen</div>
                  <div className="set-row-sub">Herstel naar standaardgegevens</div>
                </div>
                <button className="btn btn-sm" style={{ background: "rgba(210,122,107,0.14)", color: "var(--bad)" }} onClick={resetAll}>Wissen</button>
              </div>
            </div>
          </div>

          <div style={{ textAlign: "center", fontSize: 11.5, color: "var(--text-3)", fontWeight: 600 }}>
            Alle gegevens worden lokaal in je browser bewaard.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ACCENTS, applyAccent, hexToRgba, darken, SettingsModal });
