/* ============================================================
   PROGRESS PORTFOLIO v2 — TaskPicker + LogModal (shared)
   ============================================================ */
function catChips(task) {
  const P = window.PP;
  const cats = {};
  (task.fields || []).forEach((f) => Object.keys(f.stats || {}).forEach((s) => (cats[s] = true)));
  return Object.keys(cats);
}

function TaskPicker({ customTasks, onPick, onClose, onCreateCustom, onPickEphemeral, onDeleteCustom }) {
  const P = window.PP;
  const [q, setQ] = useState("");
  const [group, setGroup] = useState("All");
  const [creating, setCreating] = useState(false);
  const saved = customTasks || [];
  // search includes saved personal-db tasks; ephemeral tasks never appear in the list
  const all = [...(P.TASKS || []), ...saved];
  const groups = ["All", ...P.TASK_GROUPS, ...(saved.length > 0 ? ["My Database"] : [])];
  const filtered = all.filter((t) => {
    if (group === "My Database") return !!t.custom;
    if (group !== "All" && t.group !== group) return false;
    if (q && !t.name.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  function makeTaskDef(name, requireNotes) {
    const task = { id: "custom_" + Date.now().toString(36), name, group: "Custom", custom: true, requireNotes: requireNotes || false, fields: [{ key: "done", label: "Done", unit: "pts", default: 1, stats: {}, quick: true }] };
    return task;
  }

  function CreateForm() {
    const [name, setName] = useState("");
    const [saveToDb, setSaveToDb] = useState(false);
    const [requireNotes, setRequireNotes] = useState(false);
    function submit() {
      if (!name.trim()) return;
      const task = makeTaskDef(name.trim(), requireNotes);
      if (saveToDb) { onCreateCustom && onCreateCustom(task); onPick(task.id); }
      else { onPickEphemeral && onPickEphemeral(task); }
    }
    return (
      <div className="create-form">
        <Field label="Task name"><input className="inp" autoFocus value={name} placeholder="e.g. Stretch before bed" onChange={(e) => setName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") submit(); }} /></Field>
        <label className="save-db-toggle">
          <input type="checkbox" checked={saveToDb} onChange={(e) => setSaveToDb(e.target.checked)} />
          <span>Save to my personal database</span>
        </label>
        <label className="save-db-toggle">
          <input type="checkbox" checked={requireNotes} onChange={(e) => setRequireNotes(e.target.checked)} />
          <span>Require notes on completion</span>
        </label>
        <div className="field-hint dim" style={{ fontSize: 11 }}>{saveToDb ? "Will appear in searches and can be reused any day." : "One-time use — added to today only, not saved to your database."}</div>
        <div className="row-inline" style={{ justifyContent: "flex-end", gap: 8 }}>
          <button className="btn btn-sm" onClick={() => setCreating(false)}>Cancel</button>
          <button className="btn btn-sm btn-accent" disabled={!name.trim()} onClick={submit}>Add task</button>
        </div>
      </div>
    );
  }

  return (
    <Modal open wide onClose={onClose} title="Add a task"
      footer={<button className="btn" onClick={onClose}>Done</button>}>
      {creating ? <CreateForm /> : (
        <>
          <div className="picker-top">
            <input className="inp" placeholder="Search the task database…" value={q} onChange={(e) => setQ(e.target.value)} autoFocus />
            <button className="btn btn-sm btn-accent" onClick={() => setCreating(true)}>+ Custom</button>
          </div>
          <div className="picker-groups">
            {groups.map((g) => <button key={g} className={"chip" + (group === g ? " on" : "")} onClick={() => setGroup(g)}>{g}</button>)}
          </div>
          <div className="picker-list">
            {filtered.length === 0 && <Empty>No tasks match. Try "+ Custom".</Empty>}
            {filtered.map((t) => (
              <div className="picker-item-wrap" key={t.id}>
                <button className="picker-item" style={{ flex: 1 }} onClick={() => onPick(t.id)}>
                  <div className="picker-item-main">
                    <span className="picker-item-name">{t.name}{t.scalable && <span className="scalable-tag">set amount</span>}{t.custom && <span className="custom-tag">saved</span>}</span>
                    <span className="picker-item-meta mono dim">{t.custom ? "Personal DB" : t.group} · {(t.fields[0] && t.fields[0].unit) || "—"}</span>
                  </div>
                  <div className="picker-item-cats">{catChips(t).map((c) => <StatChip key={c} stat={c} />)}</div>
                  <span className="picker-add">+</span>
                </button>
                {t.custom && onDeleteCustom && (
                  <button className="picker-item-del" title="Remove from personal database" onClick={(e) => { e.stopPropagation(); if (confirm('Remove "' + t.name + '" from your personal database?')) onDeleteCustom(t.id); }}>✕</button>
                )}
              </div>
            ))}
          </div>
        </>
      )}
    </Modal>
  );
}

/* log a task's field values (+ optional quality / skill / income / subtype) */
function LogModal({ task, existing, onSave, onClose, dateLabel, defaults, onSetDefault, skills }) {
  const P = window.PP;
  const td = (defaults && defaults[task.id]) || null;
  const userSkills = Object.values(skills || {});
  const [vals, setVals] = useState(() => {
    const v = {}; task.fields.forEach((f) => (v[f.key] = (existing && existing.values && existing.values[f.key] != null) ? existing.values[f.key] : (td && td[f.key] != null ? td[f.key] : f.default)));
    return v;
  });
  const [remember, setRemember] = useState(false);
  const [taskNote, setTaskNote] = useState((existing && existing.taskNote) || "");
  const [quality, setQuality] = useState(existing && existing.quality || { intensity: 4, feel: 4, note: "" });
  const defaultSkill = userSkills.length > 0 ? userSkills[0].name : "Guitar";
  const [skill, setSkill] = useState(existing && existing.skill || { skill: defaultSkill, skillId: (userSkills[0] && userSkills[0].id) || "", what: "" });
  const [income, setIncome] = useState(existing && existing.income || { amount: 0, source: "Dad", desc: task.name });
  // Feature 6: logSubtype support
  const [subtype, setSubtype] = useState((existing && existing.subtype) || (task.logSubtype && task.logSubtype[0]) || "");
  const fallbackSkillNames = ["Guitar", "Piano", "Language", "Drawing", "Design", "Coding", "Lockpicking", "BJJ", "Carpentry", "Music theory", "Other"];
  const requireNotes = task && task.requireNotes;

  const canSave = !requireNotes || taskNote.trim();
  return (
    <Modal open onClose={onClose} title={task.name}
      footer={<button className="btn btn-accent" disabled={!canSave} onClick={() => {
        const log = { done: true, values: vals };
        if (task.logQuality) log.quality = quality;
        if (task.logSkill) log.skill = skill;
        if (task.logSubtype && task.logSubtype.length > 0) log.subtype = subtype;
        if (taskNote.trim()) log.taskNote = taskNote.trim();
        let incomeEntry = null;
        if (task.logIncome && Number(income.amount) > 0) { log.income = income; incomeEntry = { source: income.source, desc: income.desc, amount: Number(income.amount), minutes: Number(vals.min) || 0 }; }
        if (remember && onSetDefault) onSetDefault(task.id, vals);
        onSave(log, incomeEntry);
      }}>{requireNotes && !taskNote.trim() ? "Add notes to save" : "Save"}</button>}>
      <div className="stack">
        {dateLabel && <div className="dim" style={{ fontSize: 12, fontFamily: "var(--mono)" }}>{dateLabel}</div>}
        {/* Feature 6: logSubtype dropdown — shown before numeric fields */}
        {task.logSubtype && task.logSubtype.length > 0 && (
          <Field label="Type">
            <select className="inp" value={subtype} onChange={(e) => setSubtype(e.target.value)}>
              {task.logSubtype.map((o) => <option key={o}>{o}</option>)}
            </select>
          </Field>
        )}
        {task.fields.filter((f) => !f.quick || task.fields.length === 1).map((f) => (
          <Field key={f.key} label={f.label + " (" + f.unit + ")"}>
            <input className="inp" type="number" value={vals[f.key]} onChange={(e) => setVals({ ...vals, [f.key]: Number(e.target.value) || 0 })} />
          </Field>
        ))}
        <div className="contrib-preview">
          {(() => {
            const tot = {}; task.fields.forEach((f) => { const v = vals[f.key]; Object.keys(f.stats || {}).forEach((s) => (tot[s] = (tot[s] || 0) + v * f.stats[s])); });
            return Object.keys(tot).map((s) => <span key={s} className="contrib"><StatChip stat={s} /> +{Math.round(tot[s])} {P.CATS[s].unit}</span>);
          })()}
        </div>
        {onSetDefault && task.fields.some((f) => !f.quick || task.fields.length === 1) && (
          <button type="button" className={"remember-default" + (remember ? " on" : "")} onClick={() => setRemember(!remember)}>
            <span className="rd-box">{remember && "✓"}</span>
            Remember this amount as my default for "{task.name}"
          </button>
        )}
        {task.logQuality && (
          <>
            <Field label="Intensity"><Rating value={quality.intensity} onChange={(n) => setQuality({ ...quality, intensity: n })} icon="◆" /></Field>
            <Field label="How it felt"><Rating value={quality.feel} onChange={(n) => setQuality({ ...quality, feel: n })} /></Field>
            <Field label="Notes (PRs, what to beat)"><textarea className="ta" rows={2} value={quality.note} onChange={(e) => setQuality({ ...quality, note: e.target.value })} placeholder="e.g. Bench 3x8 @ 135..." /></Field>
          </>
        )}
        {task.logSkill && (
          <>
            {userSkills.length > 0 ? (
              <Field label="Which skill?">
                <select className="inp" value={skill.skillId || ""} onChange={(e) => {
                  const sk = userSkills.find((s) => s.id === e.target.value);
                  setSkill({ ...skill, skillId: e.target.value, skill: sk ? sk.name : skill.skill });
                }}>
                  {userSkills.map((s) => <option key={s.id} value={s.id}>{s.icon} {s.name}</option>)}
                  <option value="">Other / not listed</option>
                </select>
                <div className="dim" style={{ fontSize: 11, marginTop: 3 }}>Add more skills in the Skills tab.</div>
              </Field>
            ) : (
              <Field label="Which skill?">
                <select className="inp" value={skill.skill} onChange={(e) => setSkill({ ...skill, skill: e.target.value })}>
                  {fallbackSkillNames.map((s) => <option key={s}>{s}</option>)}
                </select>
                <div className="dim" style={{ fontSize: 11, marginTop: 3 }}>Set up skills in the Skills tab to track progress there too.</div>
              </Field>
            )}
            <Field label="What did you work on?"><textarea className="ta" rows={2} value={skill.what} onChange={(e) => setSkill({ ...skill, what: e.target.value })} placeholder="e.g. single-pin picking..." /></Field>
          </>
        )}
        {task.logIncome && (
          <div className="income-mini">
            <div className="dd-section-label">EARN MONEY? (optional)</div>
            <div className="row2">
              <Field label="Amount ($)"><input className="inp" type="number" value={income.amount} onChange={(e) => setIncome({ ...income, amount: e.target.value })} /></Field>
              <Field label="Source"><select className="inp" value={income.source} onChange={(e) => setIncome({ ...income, source: e.target.value })}>{["Dad", "Freelance", "Sales", "Content", "Other"].map((s) => <option key={s}>{s}</option>)}</select></Field>
            </div>
          </div>
        )}
        <Field label={requireNotes ? "Notes (required)" : "Notes (optional)"}><textarea className="ta" rows={2} value={taskNote} placeholder="Any notes about this session..." onChange={(e) => setTaskNote(e.target.value)} style={requireNotes && !taskNote.trim() ? { borderColor: "var(--danger)" } : {}} /></Field>
      </div>
    </Modal>
  );
}

Object.assign(window, { TaskPicker, LogModal, catChips });
