/* =========================================================================
   Çevik Yaşam — AYARLAR (hardcoded değerlerin hepsi buradan ayarlanır)
   Değişiklikler cy:cfg-* anahtarlarına yazılır; data.js bunları okur.
   "Kaydet ve uygula" → sayfayı yeniler, ayarlar her yere işler.
   ========================================================================= */

function SettingsSection({ icon, title, sub, children, right }) {
  return (
    <Card style={{ marginBottom: 18 }}>
      <div className="cy-between" style={{ alignItems: "flex-start", marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 12 }}>
          <div className="cy-rem-ic" style={{ width: 36, height: 36, background: "var(--ml-red-050)", color: "var(--ml-red)" }}><Icon name={icon} className="ic" /></div>
          <div>
            <h3 className="cy-h4" style={{ fontSize: 16 }}>{title}</h3>
            {sub && <div className="cy-muted" style={{ fontSize: 12.5, marginTop: 3 }}>{sub}</div>}
          </div>
        </div>
        {right}
      </div>
      {children}
    </Card>
  );
}

function Field({ label, value, onChange, placeholder, textarea, type }) {
  return (
    <div className="cy-field" style={{ marginBottom: 14 }}>
      <label className="cy-label">{label}</label>
      {textarea
        ? <textarea className="cy-textarea" rows={3} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} />
        : <input className="cy-input" type={type || "text"} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} />}
    </div>
  );
}

function Ayarlar() {
  const [profile, setProfile] = useState({ ...CY.profile });
  const [general, setGeneral] = useState({ ...CY.general });
  const [values, setValues] = useState(CY.values.map((v) => ({ ...v })));
  const [groups, setGroups] = useState(CY.groups.map((g) => ({ ...g })));
  const [projects, setProjects] = useState(CY.projects.map((p) => ({ id: p.id, name: p.name, group: p.group })));
  const [subs, setSubs] = useState(CY.subprojects.map((s) => ({ ...s })));
  const [reset, setReset] = useState(null);

  const pset = (k, v) => setProfile((s) => ({ ...s, [k]: v }));
  const gset = (k, v) => setGeneral((s) => ({ ...s, [k]: v }));
  const slug = (s) => (s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || ("g" + Date.now().toString(36));

  const save = () => {
    const subsClean = subs.filter((s) => s.name.trim());
    const entries = {
      "cy:cfg-profile": profile,
      "cy:cfg-general": { ...general, focusRule: Number(general.focusRule) || 2, stressCeiling: Number(general.stressCeiling) || 6 },
      "cy:cfg-values": values.filter((v) => v.label.trim()),
      "cy:cfg-groups": groups.filter((g) => g.label.trim()),
      "cy:cfg-projects": projects.filter((p) => p.name.trim()),
      "cy:subprojects": subsClean,
      "cy:cfg-subprojects": subsClean,
    };
    try { Object.keys(entries).forEach((k) => localStorage.setItem(k, JSON.stringify(entries[k]))); } catch (e) {}
    try { if (window.CY_STATE) Object.keys(entries).forEach((k) => { window.CY_STATE[k] = entries[k]; }); } catch (e) {}
    try { Object.keys(entries).forEach((k) => window.cySaveState && window.cySaveState(k, entries[k])); } catch (e) {}
    (window.cyFlushState ? window.cyFlushState() : Promise.resolve()).then(() => location.reload());
  };
  const doReset = (factory) => {
    const keep = (k) => k.startsWith("cy:cfg-") || k === "cy:onboarded" || k === "cy:tab" || k === "cy:view";
    if (factory) {
      try { Object.keys(localStorage).forEach((k) => { if (k.startsWith("cy:")) localStorage.removeItem(k); }); } catch (e) {}
      try { if (window.CY_STATE) Object.keys(window.CY_STATE).forEach((k) => delete window.CY_STATE[k]); } catch (e) {}
      const done = () => location.reload();
      (window.cyClearState ? window.cyClearState() : Promise.resolve()).then(done, done);
      return;
    }
    // ilerlemeyi sıfırla: cfg-*, onboarded, tab, view hariç her şeyi sil
    const removed = new Set();
    try { Object.keys(localStorage).forEach((k) => { if (k.startsWith("cy:") && !keep(k)) { removed.add(k); localStorage.removeItem(k); } }); } catch (e) {}
    try { if (window.CY_STATE) Object.keys(window.CY_STATE).forEach((k) => { if (k.startsWith("cy:") && !keep(k)) { removed.add(k); delete window.CY_STATE[k]; } }); } catch (e) {}
    try { removed.forEach((k) => window.cySaveState && window.cySaveState(k, null)); } catch (e) {}
    (window.cyFlushState ? window.cyFlushState() : Promise.resolve()).then(() => location.reload());
  };

  return (
    <div className="cy-canvas narrow cy-fade-in" style={{ paddingBottom: 120 }}>
      <SectionHead eyebrow="Yapılandırma" title="Ayarlar"
        sub="Profilin, değerlerin, proje ağacın ve genel parametrelerin — hepsi buradan. Değişiklikler “Kaydet ve uygula” ile tüm uygulamaya işler." />

      {/* PROFİL */}
      <SettingsSection icon="compass" title="Profil" sub="Selamlama, kenar çubuğu ve “Şu an neredeyim” bu bilgileri kullanır.">
        <div className="cy-grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 0, columnGap: 16 }}>
          <Field label="Ad" value={profile.name} onChange={(v) => pset("name", v)} />
          <Field label="Baş harf (avatar)" value={profile.initials} onChange={(v) => pset("initials", v)} />
          <Field label="Rol / unvan" value={profile.role} onChange={(v) => pset("role", v)} />
          <Field label="Konum" value={profile.location} onChange={(v) => pset("location", v)} />
        </div>
        <Field label="Şu an neredeyim" textarea value={profile.whereami} onChange={(v) => pset("whereami", v)} />
      </SettingsSection>

      {/* GENEL */}
      <SettingsSection icon="settings" title="Genel" sub="Tarih otomatik; çevik parametreleri ayarla.">
        <div className="cy-card tint" style={{ padding: 14, marginBottom: 14, display: "flex", gap: 10, alignItems: "center" }}>
          <Icon name="clock" style={{ width: 17, color: "var(--ml-red)", flex: "none" }} />
          <div style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ml-ink-2)" }}>
            Gün ve hafta <strong>otomatik</strong> güncelleniyor: <b>{CY.today.label}</b> · {CY.today.week} ({CY.today.range}).
          </div>
        </div>
        <div className="cy-grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 0, columnGap: 16 }}>
          <Field label="Aktif odak kuralı (kaç platform?)" type="number" value={general.focusRule} onChange={(v) => gset("focusRule", v)} />
          <Field label="Makul stres üst sınırı (1–10)" type="number" value={general.stressCeiling} onChange={(v) => gset("stressCeiling", v)} />
        </div>
      </SettingsSection>

      {/* DEĞERLER */}
      <SettingsSection icon="heart" title="Değerler" sub="“Değerlerimle uyumlu tatminli yaşam” — onboarding ve profilde görünür."
        right={<Btn variant="ghost" size="sm" icon="plus" onClick={() => setValues((vs) => [...vs, { id: uid("v"), label: "", note: "" }])}>Değer ekle</Btn>}>
        <div className="cy-stack" style={{ gap: 10 }}>
          {values.map((v, i) => (
            <div key={v.id} className="cy-set-row">
              <input className="cy-input" style={{ flex: "1 1 200px" }} placeholder="Değer adı" value={v.label}
                onChange={(e) => setValues((vs) => vs.map((x, j) => j === i ? { ...x, label: e.target.value } : x))} />
              <input className="cy-input" style={{ flex: "2 1 280px" }} placeholder="Kısa açıklama" value={v.note}
                onChange={(e) => setValues((vs) => vs.map((x, j) => j === i ? { ...x, note: e.target.value } : x))} />
              <button className="cy-iconbtn-sm" onClick={() => setValues((vs) => vs.filter((_, j) => j !== i))}><Icon name="trash" className="ic" /></button>
            </div>
          ))}
          {!values.length && <div className="cy-empty">Değer yok. Bir tane ekle.</div>}
        </div>
      </SettingsSection>

      {/* PROJELER: gruplar */}
      <SettingsSection icon="layoutGrid" title="Proje grupları" sub="Todoist üst kategorilerin. Renkleri her yerde etiket rengi olur."
        right={<Btn variant="ghost" size="sm" icon="plus" onClick={() => setGroups((gs) => [...gs, { key: slug("grup" + (gs.length + 1)), label: "", color: "#545458" }])}>Grup ekle</Btn>}>
        <div className="cy-stack" style={{ gap: 10 }}>
          {groups.map((g, i) => (
            <div key={g.key} className="cy-set-row">
              <input className="cy-color" type="color" value={g.color} onChange={(e) => setGroups((gs) => gs.map((x, j) => j === i ? { ...x, color: e.target.value } : x))} />
              <input className="cy-input" style={{ flex: "1 1 200px" }} placeholder="Grup adı" value={g.label}
                onChange={(e) => setGroups((gs) => gs.map((x, j) => j === i ? { ...x, label: e.target.value } : x))} />
              <span className="cy-tag-mini cy-mono">{g.key}</span>
              <button className="cy-iconbtn-sm" onClick={() => setGroups((gs) => gs.filter((_, j) => j !== i))}><Icon name="trash" className="ic" /></button>
            </div>
          ))}
        </div>
      </SettingsSection>

      {/* PROJELER: projeler */}
      <SettingsSection icon="grid" title="Projeler" sub="İşler, matris ve seyir kayıtları bu projelerle etiketlenir."
        right={<Btn variant="ghost" size="sm" icon="plus" onClick={() => setProjects((ps) => [...ps, { id: uid("p"), name: "", group: (groups[0] || {}).key }])}>Proje ekle</Btn>}>
        <div className="cy-stack" style={{ gap: 10 }}>
          {projects.map((p, i) => (
            <div key={p.id} className="cy-set-row">
              <i className="cy-proj-dot" style={{ background: (groups.find((g) => g.key === p.group) || {}).color || "var(--ml-ink-4)", width: 10, height: 10 }} />
              <input className="cy-input" style={{ flex: "1 1 200px" }} placeholder="Proje adı" value={p.name}
                onChange={(e) => setProjects((ps) => ps.map((x, j) => j === i ? { ...x, name: e.target.value } : x))} />
              <select className="cy-input" style={{ flex: "0 1 170px" }} value={p.group}
                onChange={(e) => setProjects((ps) => ps.map((x, j) => j === i ? { ...x, group: e.target.value } : x))}>
                {groups.map((g) => <option key={g.key} value={g.key}>{g.label}</option>)}
              </select>
              <button className="cy-iconbtn-sm" onClick={() => setProjects((ps) => ps.filter((_, j) => j !== i))}><Icon name="trash" className="ic" /></button>
            </div>
          ))}
        </div>
      </SettingsSection>

      {/* PROJELER: alt projeler */}
      <SettingsSection icon="layoutGrid" title="Alt projeler" sub="Bir projenin içindeki konular. ★ Esas = ana görevin; işaretsiz = ilgilendiğin yan konu. Görevler'de 'Sadece esas' ile yan konuları gizlersin."
        right={<Btn variant="ghost" size="sm" icon="plus" onClick={() => setSubs((ss) => [...ss, { id: uid("s"), project: (projects[0] || {}).id, name: "", kind: "ilgi" }])}>Alt proje ekle</Btn>}>
        <div className="cy-stack" style={{ gap: 10 }}>
          {subs.map((s, i) => (
            <div key={s.id} className="cy-set-row">
              <div className="cy-kind3">
                {["esas", "ilgi", "takip"].map((k) => (
                  <button key={k} className={"cy-kind3-btn " + k + ((s.kind || "ilgi") === k ? " on" : "")}
                    onClick={() => setSubs((ss) => ss.map((x, j) => j === i ? { ...x, kind: k } : x))}>
                    {k === "esas" ? "★ Esas" : k === "ilgi" ? "İlgi" : "Takip"}
                  </button>
                ))}
              </div>
              <input className="cy-input" style={{ flex: "1 1 180px" }} placeholder="Alt proje adı" value={s.name}
                onChange={(e) => setSubs((ss) => ss.map((x, j) => j === i ? { ...x, name: e.target.value } : x))} />
              <select className="cy-input" style={{ flex: "0 1 160px" }} value={s.project}
                onChange={(e) => setSubs((ss) => ss.map((x, j) => j === i ? { ...x, project: e.target.value } : x))}>
                {projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
              <button className="cy-iconbtn-sm" onClick={() => setSubs((ss) => ss.filter((_, j) => j !== i))}><Icon name="trash" className="ic" /></button>
            </div>
          ))}
          {!subs.length && <div className="cy-empty">Alt proje yok. Örn. İmes Spor için 5 konu ekle, 2'sini ★ Esas işaretle.</div>}
        </div>
      </SettingsSection>

      {/* ÖNCELİK HARİTASI */}
      <SettingsSection icon="flag" title="Öncelik haritası" sub="Proje + alt proje önceliklerini bir kez ayarla; Öncelik triyajı bunu kullanır.">
        <ProjectPriorityBoard embedded />
      </SettingsSection>

      {/* VERİ */}
      <SettingsSection icon="archive" title="Veri" sub="İlerlemeni sıfırla ya da örnek veriye dön.">
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <Btn variant="ghost" icon="repeat" onClick={() => setReset("progress")}>İlerlemeyi sıfırla</Btn>
          <Btn variant="ghost" icon="trash" onClick={() => setReset("factory")} style={{ color: "var(--ml-red)" }}>Fabrika ayarlarına dön</Btn>
        </div>
        <div className="cy-muted" style={{ fontSize: 12.5, marginTop: 10, lineHeight: 1.5 }}>
          “İlerlemeyi sıfırla” işleri/kayıtları örnek veriye döndürür, ayarlarını korur. “Fabrika ayarları” her şeyi (ayarlar dahil) sıfırlar.
        </div>
      </SettingsSection>

      {/* sticky kaydet */}
      <div className="cy-save-bar">
        <span className="cy-muted" style={{ fontSize: 13 }}>Değişiklikler kaydedilince uygulama yenilenir.</span>
        <Btn variant="primary" icon="check" onClick={save}>Kaydet ve uygula</Btn>
      </div>

      {reset && <ConfirmSheet
        title={reset === "factory" ? "Fabrika ayarlarına dön" : "İlerlemeyi sıfırla"}
        body={reset === "factory" ? "Tüm ayarlar ve veriler örnek haline dönecek. Emin misin?" : "İşler, seyir kayıtları, matris ve engeller örnek veriye dönecek; ayarların korunur."}
        confirmLabel={reset === "factory" ? "Her şeyi sıfırla" : "İlerlemeyi sıfırla"}
        onClose={() => setReset(null)} onConfirm={() => doReset(reset === "factory")} />}
    </div>
  );
}

Object.assign(window, { Ayarlar });
