// journal.jsx — Photo journal per folk (memories timeline)

function PhotoJournal({ folk, entries, onAdd, onRemove }) {
  const [picked, setPicked] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const [draft, setDraft] = React.useState({ note: '', photoUrl: '' });
  const fileRef = React.useRef(null);

  const items = (entries || []).slice().sort((a, b) =>
    new Date(b.date) - new Date(a.date));
  const first = items[items.length - 1];
  const latest = items[0];

  const onPick = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setDraft((d) => ({ ...d, photoUrl: ev.target.result }));
    reader.readAsDataURL(file);
  };

  const save = () => {
    if (!draft.photoUrl) return;
    onAdd && onAdd({
      id: `j-${Date.now()}`,
      date: window.TOOLS_NOW.toISOString(),
      photoUrl: draft.photoUrl,
      note: (draft.note || '').trim(),
    });
    setDraft({ note: '', photoUrl: '' });
    setAdding(false);
  };

  return (
    <>
      <window.SectionHeader kicker="Journal" title="Memories" accent={`with ${folk.name}`} count={`${items.length}`} />
      <div className="health-card journal-card">
        {items.length === 0 && !adding && (
          <div className="health-empty">
            <div className="health-empty-mark">✦</div>
            <div className="health-empty-t">No memories yet.</div>
            <div className="health-empty-s">
              Photos over time. Snap one today, then again in a month — you'll be glad later.
            </div>
          </div>
        )}

        {items.length >= 2 && (
          <div className="jr-compare">
            <div className="jr-compare-hd h-mono">Then <em>·</em> now</div>
            <div className="jr-compare-row">
              <div className="jr-compare-cell">
                <img src={first.photoUrl} alt="" />
                <div className="jr-compare-date h-mono">{fmtJournalDate(first.date)}</div>
              </div>
              <div className="jr-compare-arrow">→</div>
              <div className="jr-compare-cell">
                <img src={latest.photoUrl} alt="" />
                <div className="jr-compare-date h-mono">{fmtJournalDate(latest.date)}</div>
              </div>
            </div>
            <div className="jr-compare-sub h-mono">
              {items.length} memories · spanning {monthsBetween(first.date, latest.date)}
            </div>
          </div>
        )}

        {items.length > 0 && (
          <div className="jr-grid">
            {items.map((j) => (
              <button key={j.id} className="jr-tile" onClick={() => setPicked(j)}>
                <img src={j.photoUrl} alt="" />
                <div className="jr-tile-date h-mono">{fmtJournalDate(j.date)}</div>
              </button>
            ))}
          </div>
        )}

        {adding ? (
          <div className="health-form jr-form">
            {draft.photoUrl ? (
              <div className="jr-preview">
                <img src={draft.photoUrl} alt="" />
                <button className="jr-clear" onClick={() => setDraft({ ...draft, photoUrl: '' })}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                       strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
                </button>
              </div>
            ) : (
              <button className="health-file-btn jr-pick" onClick={() => fileRef.current?.click()}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="7" width="18" height="13" rx="2"/>
                  <circle cx="12" cy="13.5" r="3.5"/><path d="M8 7l1.5-2h5L16 7"/>
                </svg>
                <span>Pick a photo</span>
              </button>
            )}
            <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={onPick} />
            <input className="health-input" value={draft.note}
                   onChange={(e) => setDraft({ ...draft, note: e.target.value })}
                   placeholder={folk.kind === 'plant' ? 'A note — new leaf, repotted, etc.' : 'A note — first time on the porch, etc.'} />
            <div className="r-add-actions">
              <button className="r-cancel" onClick={() => { setAdding(false); setDraft({ note: '', photoUrl: '' }); }}>Cancel</button>
              <button className="r-save" onClick={save} disabled={!draft.photoUrl}
                      style={{ opacity: draft.photoUrl ? 1 : 0.4 }}>Save memory</button>
            </div>
          </div>
        ) : (
          <button className="r-add" onClick={() => setAdding(true)}>
            <span className="r-plus">+</span>
            <span>Save a memory of {folk.name}</span>
          </button>
        )}
      </div>

      {picked && (
        <div className="jr-fullscreen" onClick={() => setPicked(null)}>
          <div className="jr-fs-inner" onClick={(e) => e.stopPropagation()}>
            <img src={picked.photoUrl} alt="" className="jr-fs-img" />
            <div className="jr-fs-meta">
              <div className="jr-fs-date h-mono">{fmtJournalDate(picked.date, true)}</div>
              {picked.note && <div className="jr-fs-note h-serif"><i>"{picked.note}"</i></div>}
              <div className="jr-fs-actions">
                <button className="jr-fs-del" onClick={() => { onRemove && onRemove(picked.id); setPicked(null); }}>
                  Remove
                </button>
                <button className="jr-fs-close" onClick={() => setPicked(null)}>Done</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function fmtJournalDate(iso, long) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('en-US',
    long ? { year: 'numeric', month: 'long', day: 'numeric' }
         : { month: 'short', day: 'numeric' });
}

function monthsBetween(a, b) {
  const A = new Date(a), B = new Date(b);
  const m = (B.getFullYear() - A.getFullYear()) * 12 + (B.getMonth() - A.getMonth());
  if (m < 1) return 'this month';
  if (m === 1) return 'one month';
  if (m < 12) return `${m} months`;
  const y = Math.round(m / 12);
  return y === 1 ? 'one year' : `${y} years`;
}

window.PhotoJournal = PhotoJournal;
