/* Nelawa — reference.jsx: the Reference drawer (GTD Flow Review G3, 2026-07-12).
   Non-actionable keepers — passwords, numbers, recipe links, project notes.
   A reference item is a task with status:'reference' (never on any board, never
   in any Sweep, no counts in the nav — a drawer, not a list of debts). It can
   stand alone or be attached to a task/project via refOf (the Support pocket
   on the card is the other side of that link). Text + links only until the
   deploy backend exists — real files in localStorage would silently hit the
   ~5MB quota, and silent loss is the one sin Nelawa never commits. */

function refLinkify(text) {
  const parts = String(text || '').split(/(https?:\/\/\S+)/g);
  return parts.map((p, i) => /^https?:\/\//.test(p)
    ? <a key={i} href={p} target="_blank" rel="noopener noreferrer">{p.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '')}</a>
    : p);
}

function RefRow({ item }) {
  const { tasks } = useDumpStore();
  const linkedTo = item.refOf ? tasks.find((t) => t.id === item.refOf && !t.done) : null;
  const toss = () => {
    DumpStore.set((s) => ({ tasks: s.tasks.map((t) => (t.id === item.id ? { ...t, status: 'binned', binnedAt: new Date().toISOString() } : t)) }));
    DumpAPI.toast('Tossed — recoverable from the bin for 30 days.', {
      action: { label: 'Undo', fn: () => DumpStore.set((s) => ({ tasks: s.tasks.map((t) => (t.id === item.id ? { ...t, status: 'reference', binnedAt: null } : t)) })) }
    });
  };
  const makeTask = () => {
    DumpStore.set((s) => ({ tasks: s.tasks.map((t) => (t.id === item.id ? { ...t, status: 'active', bucket: 'next-action', gtdBucket: 'next-action', refOf: null, fresh: true } : t)) }));
    DumpAPI.toast('Moved to your board — it’s a task now.', {
      action: { label: 'View', fn: () => DumpStore.set({ route: 'tasks', tasksView: 'board' }) }
    });
  };
  return (
    <div className="ref-row">
      <span className="ref-ic">{Icons.file(15)}</span>
      <div className="ref-body">
        <p className="ref-text">{refLinkify(item.text)}</p>
        {linkedTo ? (
          <button className="ref-linked" onClick={() => DumpStore.set(linkedTo.big ? { route: 'tasks', tasksView: 'projects' } : { route: 'tasks', tasksView: 'board' })}
            title="Attached to this — tap to see it">
            {Icons.paperclip(11)} {linkedTo.text}
          </button>
        ) : null}
      </div>
      <div className="ref-acts">
        <button className="linklike" onClick={makeTask} title="Turn this into a task on your board">Make it a task</button>
        <button className="linklike danger" onClick={toss}>Toss</button>
      </div>
    </div>
  );
}

function ReferenceSection() {
  const { tasks } = useDumpStore();
  const [q, setQ] = useState('');
  const [draft, setDraft] = useState('');
  const all = tasks.filter((t) => t.status === 'reference' && !t.done);
  const shown = q.trim()
    ? all.filter((t) => t.text.toLowerCase().includes(q.trim().toLowerCase()))
    : all;
  const add = () => {
    const v = draft.trim();
    if (!v) return;
    DumpAPI.addReference(v, null);
    setDraft('');
    DumpAPI.toast('Kept — it’ll be here when you need it.');
  };
  return (
    <div className="section" data-screen-label="Reference">
      <div className="section-head">
        <h1 className="section-title">Reference</h1>
      </div>
      <p className="section-sub">
        Things to keep, not to do — passwords, numbers, links, notes. Nothing here ever nags.
        <InfoIcon text="A drawer, not a to-do list: reference items never appear on your board, on Today, or in any Sweep. Attach one to a task or project from that card’s menu (Attach a note or link)." />
      </p>

      <div className="ref-addrow">
        <input type="text" className="step-input" value={draft}
          placeholder="Keep something — “wifi password is…”, a link, a number…"
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') add(); }} />
        <button className="btn btn-primary btn-sm" onClick={add} disabled={!draft.trim()}>Keep</button>
      </div>

      {all.length > 4 ? (
        <div className="ref-searchrow">
          <input type="text" className="step-input" value={q} placeholder="Search…"
            onChange={(e) => setQ(e.target.value)} />
        </div>
      ) : null}

      {all.length === 0 ? (
        <EmptyState icon={Icons.file(26)} title="Nothing kept yet">
          Drop pure information into Capture — “the wifi password is BLUEBIRD-42” — and it lands here instead of becoming a fake task. Or attach a note or link to any task from its menu.
        </EmptyState>
      ) : shown.length === 0 ? (
        <p className="section-sub">Nothing matches “{q.trim()}”.</p>
      ) : (
        <div className="ref-list">
          {shown.map((t) => <RefRow key={t.id} item={t} />)}
        </div>
      )}
    </div>
  );
}

window.ReferenceSection = ReferenceSection;
window.RefRow = RefRow;
window.refLinkify = refLinkify;
