// Journal — write today's entry, browse what came before.
//
// The notes-service already stores one row per (user, date); we just fetch the
// whole archive (it's personal-scale) and render an ordered scroll of days.
const { useKomonichi, actions, todayKey, api } = window.KomonichiState;

function fmtDateLong(iso) {
  // 'YYYY-MM-DD' → 'Wednesday, March 5'
  const d = new Date(iso + 'T00:00:00');
  return d.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric' });
}
function fmtDateShort(iso) {
  const d = new Date(iso + 'T00:00:00');
  return d.toLocaleDateString('en', { month: 'short', day: 'numeric', year: 'numeric' });
}

function JournalPage() {
  const [state] = useKomonichi();
  const today = todayKey();
  const [archive, setArchive] = React.useState(null); // array of {date, body, updated_at}
  const [busy, setBusy] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [draft, setDraft] = React.useState(state.notes[today] || '');
  const [expanded, setExpanded] = React.useState({});
  const debounceRef = React.useRef(null);

  // load all notes on mount; refreshed when the user saves today.
  const load = React.useCallback(async () => {
    setBusy(true);
    try {
      const list = await api('/notes/');
      // Ensure today's row is present (even if blank) — server returns existing only.
      const map = new Map();
      for (const n of list) map.set(n.date, n);
      if (!map.has(today)) map.set(today, { date: today, body: state.notes[today] || '' });
      const arr = [...map.values()].sort((a, b) => b.date.localeCompare(a.date));
      setArchive(arr);
    } finally {
      setBusy(false);
    }
  }, [today]);

  React.useEffect(() => { load(); }, [load]);

  // keep draft synced with store updates from other pages
  React.useEffect(() => { setDraft(state.notes[today] || draft); }, [state.notes[today]]);

  function onChange(e) {
    const v = e.target.value;
    setDraft(v);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      setSaving(true);
      try { await actions.setDailyNote(today, v); }
      finally { setSaving(false); }
    }, 500);
  }

  const todayWords = draft.trim() ? draft.trim().split(/\s+/).length : 0;

  const previous = (archive || []).filter(n => n.date !== today && (n.body || '').trim());

  return (
    <div className="fade-in">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'end', marginBottom: 22, gap: 18 }}>
        <div>
          <div className="label">a small page kept</div>
          <h2 className="display" style={{ fontSize: 48, lineHeight: 1, margin: '8px 0 0' }}>
            journal, <span style={{ color: 'var(--persimmon)' }}>quietly written</span>
          </h2>
        </div>
        <div className="haiku" style={{ textAlign: 'right', fontSize: 14, maxWidth: 320 }}>
          <span className="line">Today's brush stroke,</span>
          <span className="line">and the strokes of all the yesterdays —</span>
          <span className="line">a paper river.</span>
        </div>
      </div>

      <div className="brush" style={{ marginBottom: 22 }}></div>

      <div className="grid g-12" style={{ gap: 22 }}>
        {/* today */}
        <div className="c-7">
          <div className="card">
            <div className="cap">
              <div>
                <div className="label">today · {fmtDateLong(today)}</div>
                <h3 className="title">a new <span className="em">entry</span></h3>
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <span className="chip">{todayWords} words</span>
                <span className="chip" style={{ opacity: saving ? 1 : 0.45 }}>{saving ? 'saving…' : 'saved'}</span>
              </div>
            </div>
            <textarea
              className="f journal-paper"
              placeholder="What is asking to be written today?"
              value={draft}
              onChange={onChange}
              style={{ minHeight: 360 }}
            />
            <div className="label" style={{ marginTop: 10, opacity: 0.7, fontStyle: 'italic' }}>
              Saved automatically. There is no submit button — just leave it when you're done.
            </div>
          </div>
        </div>

        {/* archive */}
        <div className="c-5">
          <div className="card">
            <div className="cap">
              <div>
                <div className="label">what came before</div>
                <h3 className="title"><span className="em">archive</span></h3>
              </div>
              <span className="chip">{previous.length}</span>
            </div>
            {busy && !archive ? (
              <div className="haiku" style={{ padding: '20px 0', fontSize: 13 }}>gathering pages…</div>
            ) : previous.length === 0 ? (
              <div className="haiku" style={{ padding: '20px 0', fontSize: 13 }}>
                <span className="line">No earlier entries yet.</span>
                <span className="line">Begin where you are.</span>
              </div>
            ) : (
              <div style={{ display: 'grid', gap: 0 }}>
                {previous.map(n => {
                  const open = !!expanded[n.date];
                  const preview = (n.body || '').slice(0, 120).replace(/\s+/g, ' ');
                  return (
                    <div key={n.date} style={{ padding: '14px 0', borderBottom: '1px dashed var(--paper-line)' }}>
                      <button
                        onClick={() => setExpanded(s => ({ ...s, [n.date]: !s[n.date] }))}
                        style={{ all: 'unset', cursor: 'pointer', width: '100%', display: 'block' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
                          <div className="display" style={{ fontSize: 16 }}>{fmtDateShort(n.date)}</div>
                          <div className="label" style={{ fontSize: 9 }}>{open ? '−' : '+'}</div>
                        </div>
                        {!open && preview ? (
                          <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 4, fontStyle: 'italic', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            {preview}{(n.body || '').length > 120 ? '…' : ''}
                          </div>
                        ) : null}
                      </button>
                      {open ? (
                        <div className="fade-in journal-paper-read" style={{ marginTop: 10 }}>
                          {n.body || <em style={{ color: 'var(--ink-ghost)' }}>(blank)</em>}
                        </div>
                      ) : null}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.JournalPage = JournalPage;
