/* FreeSize — Einstellungen (Settings) view */
function SettingsView({ tweaks, setTweak, nav }) {
  const { fmt } = window.FZ;
  const volumes = window.VOLUMES;
  const [licensed, setLicensed] = React.useState(false);
  const [key, setKey] = React.useState("");
  const [licMsg, setLicMsg] = React.useState(null);
  const [autoSync, setAutoSync] = React.useState(true);
  const [interval, setIntervalMin] = React.useState(60);
  const [monitored, setMonitored] = React.useState(new Set());
  const [saved, setSaved] = React.useState(false);
  const savedT = React.useRef(null);

  const activate = () => {
    if (key.trim().length < 6) { setLicMsg({ ok: false, t: "Bitte einen gültigen Lizenzschlüssel eingeben." }); return; }
    setLicensed(true);
    setLicMsg({ ok: true, t: "Lizenz erfolgreich aktiviert. Willkommen bei FreeSize Pro!" });
  };
  const save = () => {
    setSaved(true);
    clearTimeout(savedT.current);
    savedT.current = setTimeout(() => setSaved(false), 2200);
  };
  const toggleVol = (id) => setMonitored((p) => { const n = new Set(p); n.has(id) ? n.delete(id) : n.add(id); return n; });

  const ToggleSwitch = ({ on, onClick }) => (
    <button className={"check" + (on ? " on" : "")} onClick={onClick}
      style={{ width: 44, height: 26, borderRadius: 30, position: "relative", flex: "none" }}>
      <span style={{ position: "absolute", top: 2, left: on ? 20 : 2, width: 20, height: 20, borderRadius: "50%", background: "#fff", transition: "left .16s", boxShadow: "0 1px 2px rgba(0,0,0,.25)" }} />
    </button>
  );

  const proOverlay = (
    <div className="pro-overlay"><span className="po-badge"><IconLock size={13} /> Nur in FreeSize Pro</span></div>
  );

  return (
    <React.Fragment>
      <header className="appbar settings-bar">
        <Logo iconSize={26} showSub={false} />
        <div className="appbar-spacer" />
        <div className="tabs">
          <button className="tab" title="Scan" onClick={() => nav.setView("scan")}><IconRadar size={17} /></button>
          <button className="tab active" title="Einstellungen" onClick={() => nav.setView("settings")}><IconSettings size={17} /></button>
        </div>
      </header>

      <div className="settings-scroll">
        <div className="settings">
          <div className="settings-h">
            <h1>Einstellungen</h1>
            <p>Erscheinungsbild, Lizenz, Synchronisierung und überwachte Volumes verwalten.</p>
          </div>

          {/* ---- Appearance ---- */}
          <div className="card">
            <div className="card-h">
              <span className="ci">{tweaks.dark ? <IconMoon size={17} /> : <IconSun size={17} />}</span>
              <div><h2>Erscheinungsbild</h2><p>Helles oder dunkles Design.</p></div>
            </div>
            <div className="card-b">
              <div className="row-line">
                <div className="rl-main">
                  <div className="rl-title">Dunkles Design</div>
                  <div className="rl-sub">Dunkle Oberfläche für wenig Umgebungslicht.</div>
                </div>
                <ToggleSwitch on={tweaks.dark} onClick={() => setTweak("dark", !tweaks.dark)} />
              </div>
            </div>
          </div>

          {/* ---- License ---- */}
          <div className="card">
            <div className="card-h">
              <span className="ci"><IconSpark size={17} /></span>
              <div><h2>Lizenz</h2><p>Status deiner FreeSize-Aktivierung.</p></div>
              <div style={{ marginLeft: "auto" }}>
                {licensed
                  ? <span className="pill ok"><IconCheck size={14} stroke={2.6} /> FreeSize Pro aktiv</span>
                  : <span className="pill warn"><IconLock size={13} /> Nicht aktiviert</span>}
              </div>
            </div>
            <div className="card-b">
              {licensed ? (
                <div className="lic-active">
                  <span className="lic-ic"><IconCheck size={22} stroke={2.6} /></span>
                  <div style={{ flex: 1 }}>
                    <div className="lic-t">FreeSize Pro</div>
                    <div className="lic-s">Hintergrund-Synchronisierung und Portal-Metriken sind freigeschaltet.</div>
                  </div>
                  <button className="btn btn-ghost" onClick={() => { setLicensed(false); setLicMsg(null); setKey(""); }}>Deaktivieren</button>
                </div>
              ) : (
                <div className="upsell">
                  <div className="up-main">
                    <div style={{ fontWeight: 700, fontSize: 14.5 }}>Auf FreeSize Pro upgraden</div>
                    <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 3 }}>
                      Schalte die kontinuierliche Überwachung und das Portal-Dashboard für all deine Geräte frei.
                    </div>
                    <ul className="feat">
                      {["Automatische Metrik-Synchronisierung", "Volume-Überwachung im Hintergrund", "Verlauf & Trends im FreeSize-Portal", "Mehrere Geräte zentral verwalten"].map((f) => (
                        <li key={f}><span className="fk"><IconCheck size={15} stroke={2.6} /></span>{f}</li>
                      ))}
                    </ul>
                    <div className="up-key">
                      <input className="input" placeholder="Lizenzschlüssel  z. B. FSP-XXXX-XXXX-XXXX" value={key}
                        onChange={(e) => setKey(e.target.value)} />
                      <button className="btn btn-primary" onClick={activate}>Aktivieren</button>
                    </div>
                    {licMsg && (
                      <div style={{ marginTop: 10, fontSize: 13, fontWeight: 600, color: licMsg.ok ? "var(--success)" : "var(--danger)" }}>
                        {licMsg.t}
                      </div>
                    )}
                  </div>
                  <div className="pro-aside">
                    <div>
                      <div className="pa-tag">FreeSize Pro</div>
                      <div className="pa-price">CHF 29<small>/Jahr</small></div>
                    </div>
                    <button className="btn" style={{ background: "#fff", color: "var(--accent-2)", border: "none", justifyContent: "center" }}>
                      Pro kaufen <IconArrowRight size={15} />
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* ---- Sync (Pro) ---- */}
          <div className={"card" + (licensed ? "" : " pro-locked")}>
            <div className="card-h">
              <span className="ci"><IconSync size={17} /></span>
              <div><h2>Synchronisierung</h2><p>Volume-Metriken an das FreeSize-Portal senden.</p></div>
            </div>
            <div className="card-b">
              <div className="row-line">
                <div className="rl-main">
                  <div className="rl-title">Automatische Metrik-Synchronisierung</div>
                  <div className="rl-sub">Sendet regelmässig Auslastungsdaten der überwachten Volumes.</div>
                </div>
                <ToggleSwitch on={autoSync} onClick={() => setAutoSync((s) => !s)} />
              </div>
              <div className="row-line">
                <div className="rl-main">
                  <div className="rl-title">Intervall</div>
                  <div className="rl-sub">Wie oft Metriken gesendet werden.</div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <input className="input" type="number" min="5" value={interval} onChange={(e) => setIntervalMin(Math.max(5, +e.target.value || 5))}
                    style={{ width: 86, opacity: autoSync ? 1 : 0.5 }} disabled={!autoSync} />
                  <span style={{ color: "var(--muted)", fontSize: 13 }}>Minuten</span>
                </div>
              </div>
              <div className="row-line">
                <div className="rl-main"><div className="rl-title">Letzte Synchronisierung</div></div>
                <span className="rl-val">{autoSync ? "Heute, 14:32" : "—"}</span>
              </div>
            </div>
            {!licensed && proOverlay}
          </div>

          {/* ---- Monitored volumes (Pro) ---- */}
          <div className={"card" + (licensed ? "" : " pro-locked")}>
            <div className="card-h">
              <span className="ci"><IconHardDrive size={17} /></span>
              <div><h2>Überwachte Volumes</h2><p>Ohne Auswahl werden alle erkannten Volumes überwacht.</p></div>
            </div>
            <div className="card-b" style={{ paddingTop: 6 }}>
              {volumes.map((v) => (
                <div className="vol-row" key={v.id} onClick={() => toggleVol(v.id)} style={{ cursor: "pointer" }}>
                  <span className={"check" + (monitored.has(v.id) ? " on" : "")}><IconCheck size={14} stroke={2.8} /></span>
                  <span className="vr-name">{v.label}</span>
                  <span style={{ color: "var(--muted)", fontSize: 12.5 }}>{v.caption}</span>
                  <span className="vr-size">{fmt(v.total)}</span>
                </div>
              ))}
            </div>
            {!licensed && proOverlay}
          </div>

          {/* ---- Actions ---- */}
          <div className="save-bar">
            <button className="btn btn-primary" onClick={save}><IconCheck size={16} stroke={2.4} /> Speichern</button>
            <span className={"saved-msg" + (saved ? " show" : "")}><IconCheck size={15} stroke={2.6} /> Gespeichert</span>
          </div>

          {/* ---- Info ---- */}
          <div className="card muted">
            <div className="card-b" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <div className="row-line" style={{ borderTop: "none", padding: "2px 0" }}>
                <div className="rl-main">
                  <div className="rl-title">Geräte-ID</div>
                  <div className="rl-sub">Für den Support — eindeutige Kennung dieses Geräts.</div>
                </div>
                <span className="rl-val" style={{ userSelect: "all", background: "var(--surface-3)", padding: "5px 9px", borderRadius: 7 }}>
                  7F3A-9C21-D8E0-4B65
                </span>
              </div>
              <div className="row-line" style={{ padding: "2px 0" }}>
                <div className="rl-main"><div className="rl-title">Version</div></div>
                <span className="rl-val">FreeSize 0.1.0</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}
window.SettingsView = SettingsView;
