/* ============================================================
   PROGRESS PORTFOLIO v2 — Preset editor
   ============================================================ */
function Presets({ me, updateMe, friends }) {
  const P = window.PP;
  const [editing, setEditing] = useState(null); // preset id
  const [picker, setPicker] = useState(null); // section index to add into
  const [importing, setImporting] = useState(false);

  function mutate(fn) { updateMe((m) => fn(m)); }

  const presets = Object.values(me.presets);

  if (!editing) {
    return (
      <div className="presets">
        <div className="ql-head">
          <div>
            <div className="ql-date">Presets</div>
            <div className="ql-quote">Your day templates. You start with none — import a pack or build your own.</div>
          </div>
          <div className="pe-head-actions">
            <button className="btn" onClick={() => setImporting(true)}>↓ Import</button>
            <button className="btn btn-accent" onClick={() => {
              const id = "p" + Date.now().toString(36);
              mutate((m) => (m.presets[id] = { id, name: "New Preset", tag: "Custom", sections: [{ title: "My Day", tasks: [] }] }));
              setEditing(id);
            }}>+ New preset</button>
          </div>
        </div>
        {presets.length === 0 && <Empty>No presets yet. Tap “↓ Import” to grab Flint's Presets or a friend's, or build your own.</Empty>}
        <div className="preset-cards">
          {presets.map((p) => {
            const count = p.sections.reduce((a, s) => a + s.tasks.length, 0);
            return (
              <div className="preset-card-wrap" key={p.id}>
              <button className="preset-card" onClick={() => setEditing(p.id)}>
                <div className="preset-card-name">{p.name}</div>
                <div className="preset-card-tag mono">{p.tag}</div>
                <div className="preset-card-meta mono dim">{p.sections.length} sections · {count} tasks</div>
              </button>
              <button className="preset-card-del" title="Delete preset" onClick={(e) => { e.stopPropagation(); if (confirm("Delete preset: " + p.name + "?")) mutate((m) => delete m.presets[p.id]); }}>✕</button>
            </div>
            );
          })}
        </div>
        {importing && <ImportPresetsModal me={me} friends={friends} onClose={() => setImporting(false)} onImport={(srcPresets, label) => {
          mutate((m) => { Object.values(srcPresets).forEach((p) => { const nid = "imp_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 5); m.presets[nid] = JSON.parse(JSON.stringify({ ...p, id: nid })); }); });
          setImporting(false);
        }} />}
        {(me.sectionTemplates || []).length > 0 && (
          <div className="saved-sections-panel">
            <div className="ql-date" style={{marginTop:28,marginBottom:8}}>Saved Sections</div>
            <div className="dim mono" style={{fontSize:11,marginBottom:10}}>Pin a section from any day (tap 📌 in Sections mode) to reuse it in any preset below.</div>
            <div className="saved-sec-list">
              {(me.sectionTemplates || []).map((tpl) => (
                <div className="saved-sec-row" key={tpl.id}>
                  <span className="saved-sec-title">{tpl.title}</span>
                  <span className="mono dim saved-sec-count">{tpl.tasks.length} tasks</span>
                  <button className="mini-btn btn-danger-ghost" onClick={() => mutate((m) => { m.sectionTemplates = (m.sectionTemplates || []).filter((t) => t.id !== tpl.id); })} title="delete saved section">✕</button>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }

  const preset = me.presets[editing];
  if (!preset) { setEditing(null); return null; }

  function setField(k, v) { mutate((m) => (m.presets[editing][k] = v)); }
  function addSection() { mutate((m) => m.presets[editing].sections.push({ title: "New Section", tasks: [] })); }
  function delSection(si) { mutate((m) => m.presets[editing].sections.splice(si, 1)); }
  function renameSection(si, v) { mutate((m) => (m.presets[editing].sections[si].title = v)); }
  function addToSection(si, taskId) { mutate((m) => m.presets[editing].sections[si].tasks.push(taskId)); }
  function removeTask(si, ti) { mutate((m) => m.presets[editing].sections[si].tasks.splice(ti, 1)); }
  function moveTask(si, ti, dir) { mutate((m) => { const arr = m.presets[editing].sections[si].tasks; const j = ti + dir; if (j < 0 || j >= arr.length) return; const t = arr[ti]; arr[ti] = arr[j]; arr[j] = t; }); }
  function moveSection(si, dir) { mutate((m) => { const arr = m.presets[editing].sections; const j = si + dir; if (j < 0 || j >= arr.length) return; const t = arr[si]; arr[si] = arr[j]; arr[j] = t; }); }

  return (
    <div className="presets">
      <div className="pe-head">
        <button className="btn btn-sm" onClick={() => setEditing(null)}>← All presets</button>
        <div className="pe-head-actions">
          <button className="btn btn-sm btn-danger" onClick={() => { if (confirm("Delete preset: " + preset.name + "?")) { mutate((m) => delete m.presets[editing]); setEditing(null); } }}>Delete preset</button>
        </div>
      </div>
      <div className="pe-meta">
        <Field label="Preset name"><input className="inp" value={preset.name} onChange={(e) => setField("name", e.target.value)} /></Field>
        <Field label="Tag"><input className="inp" value={preset.tag} onChange={(e) => setField("tag", e.target.value)} /></Field>
      </div>

      <div className="pe-sections">
        {preset.sections.map((sec, si) => (
          <div className="pe-section" key={si}>
            <div className="pe-section-head">
              <input className="pe-section-title" value={sec.title} onChange={(e) => renameSection(si, e.target.value)} />
              <div className="pe-section-tools">
                <button className="mini-btn" onClick={() => moveSection(si, -1)}>↑</button>
                <button className="mini-btn" onClick={() => moveSection(si, 1)}>↓</button>
                <button className="mini-btn" onClick={() => delSection(si)}>✕</button>
              </div>
            </div>
            <div className="pe-tasks">
              {sec.tasks.length === 0 && <div className="pe-empty mono dim">no tasks — add some ↓</div>}
              {sec.tasks.map((tid, ti) => {
                const t = P.taskById(tid);
                return (
                  <div className="pe-task" key={ti}>
                    <span className="pe-task-name">{t ? t.name : tid}</span>
                    <div className="pe-task-cats">{t && catChips(t).map((c) => <StatChip key={c} stat={c} />)}</div>
                    <div className="pe-task-tools">
                      <button className="mini-btn" onClick={() => moveTask(si, ti, -1)}>↑</button>
                      <button className="mini-btn" onClick={() => moveTask(si, ti, 1)}>↓</button>
                      <button className="mini-btn" onClick={() => removeTask(si, ti)}>✕</button>
                    </div>
                  </div>
                );
              })}
            </div>
            <button className="btn btn-sm" onClick={() => setPicker(si)}>+ Add task</button>
          </div>
        ))}
      </div>
      <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
        <button className="add-task-btn" onClick={addSection}>+ Add section</button>
        {(me.sectionTemplates || []).length > 0 && (
          <select className="preset-select" defaultValue="" onChange={(e) => {
            if (!e.target.value) return;
            const tpl = (me.sectionTemplates || []).find((t) => t.id === e.target.value);
            if (tpl) mutate((m) => m.presets[editing].sections.push({ title: tpl.title, tasks: [...tpl.tasks] }));
            e.target.value = "";
          }}>
            <option value="" disabled>📌 Insert saved section…</option>
            {(me.sectionTemplates || []).map((tpl) => <option key={tpl.id} value={tpl.id}>{tpl.title} ({tpl.tasks.length} tasks)</option>)}
          </select>
        )}
      </div>

      {picker != null && <TaskPicker customTasks={me.customTasks} onClose={() => setPicker(null)} onPick={(tid) => { addToSection(picker, tid); }} onCreateCustom={(task) => updateMe((m) => { m.customTasks.push(task); P.rebuildIndex(m.customTasks); })} />}
    </div>
  );
}

function ImportPresetsModal({ me, friends, onClose, onImport }) {
  const P = window.PP;
  const sources = [];
  Object.values(P.PRESET_PACKS).forEach((pack) => sources.push({ key: pack.id, label: pack.name, desc: pack.desc, presets: pack.presets, permanent: true }));
  (friends || []).forEach((f) => { if (f.presets && Object.keys(f.presets).length) sources.push({ key: f.id, label: f.meta.name + "'s Presets", desc: Object.keys(f.presets).length + " presets", presets: f.presets }); });
  return (
    <Modal open wide onClose={onClose} title="Import presets"
      footer={<button className="btn" onClick={onClose}>Done</button>}>
      <div className="import-sources">
        {sources.map((src) => (
          <div className="import-src" key={src.key}>
            <div className="import-src-head">
              <div><div className="import-src-name">{src.label}{src.permanent && <span className="custom-tag">always available</span>}</div><div className="import-src-desc mono dim">{src.desc}</div></div>
              <button className="btn btn-sm btn-accent" onClick={() => onImport(src.presets, src.label)}>Import all</button>
            </div>
            <div className="import-preset-list">
              {Object.values(src.presets).map((p) => (
                <button className="import-preset" key={p.id} onClick={() => onImport({ [p.id]: p }, src.label)}>
                  <span>{p.name}</span><span className="mono dim">{p.tag}</span><span className="picker-add">+</span>
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
    </Modal>
  );
}

Object.assign(window, { Presets, ImportPresetsModal });
