// Brain Zips — quick capture for an ADHD brain.
// Tabs: All (active) / Zips / Ideas / Done
// Each item: checkbox to mark done, flag to mark "priority/important",
// promote-to-priority action moves it into a weekly priority slot.
//
// Persistence: all items stored to localStorage via the store provider.

function BrainDump() {
  const { state, addBrainItem, deleteBrainItem, promoteBrainItem,
          toggleBrainDone, toggleBrainFlag } = useStore();
  const [tab, _setTab] = React.useState('all'); // all | dump | idea | done
  const [draft, setDraft] = React.useState('');
  const [kind, setKind] = React.useState('dump');
  const inputRef = React.useRef(null);

  // Switching tabs sets the default save-kind so typing on the Ideas tab
  // saves as an idea, typing on the Zips tab saves as a zip. (User can
  // still flip the toggle manually.)
  const setTab = (next) => {
    _setTab(next);
    if (next === 'idea') setKind('idea');
    else if (next === 'dump') setKind('dump');
    else if (next === 'all') setKind('dump'); // sensible default on All
  };

  const submit = (e) => {
    e?.preventDefault();
    if (!draft.trim()) return;
    addBrainItem(draft.trim(), kind);
    setDraft('');
    // If user is staring at the Ideas tab, they're clearly capturing ideas —
    // don't whisk it away to All. Jump them to wherever it landed.
    if (kind === 'idea' && tab !== 'idea' && tab !== 'all') _setTab('idea');
    if (kind === 'dump' && tab !== 'dump' && tab !== 'all') _setTab('dump');
    inputRef.current?.focus();
  };

  // Filter logic — fixes the previous "ideas leak everywhere" issue.
  // "All"   shows everything that's NOT done (mix of zips + ideas)
  // "Zips"  shows only kind=dump, not done
  // "Ideas" shows only kind=idea, not done
  // "Done"  shows done items regardless of kind
  const items = state.braindump.filter((b) => {
    if (tab === 'done') return b.done;
    if (b.done) return false;
    if (tab === 'all')  return true;
    return b.kind === tab;
  });

  // Flagged items float to the top within each list
  items.sort((a, b) => (b.flagged ? 1 : 0) - (a.flagged ? 1 : 0));

  const counts = {
    all:  state.braindump.filter((b) => !b.done).length,
    dump: state.braindump.filter((b) => !b.done && b.kind === 'dump').length,
    idea: state.braindump.filter((b) => !b.done && b.kind === 'idea').length,
    done: state.braindump.filter((b) =>  b.done).length,
  };

  const promoteDisabled = state.priorities.length >= 4;

  return (
    <section className="mc-card mc-bd" style={{ flex: 1, minHeight: 0 }}>
      <div className="mc-card-hd">
        <div className="lbl">
          <Icons.Brain className="ico" size={18}/>
          Brain zips
        </div>
        <div className="mc-bd-tabs">
          <button className={`mc-bd-tab ${tab === 'all'  ? 'active' : ''}`} onClick={() => setTab('all')}>
            All <span style={{ opacity: 0.5, marginLeft: 4 }}>{counts.all}</span>
          </button>
          <button className={`mc-bd-tab ${tab === 'dump' ? 'active' : ''}`} onClick={() => setTab('dump')}>
            Zips <span style={{ opacity: 0.5, marginLeft: 4 }}>{counts.dump}</span>
          </button>
          <button className={`mc-bd-tab ${tab === 'idea' ? 'active' : ''}`} onClick={() => setTab('idea')}>
            Ideas <span style={{ opacity: 0.5, marginLeft: 4 }}>{counts.idea}</span>
          </button>
          <button className={`mc-bd-tab ${tab === 'done' ? 'active' : ''}`} onClick={() => setTab('done')}>
            Done <span style={{ opacity: 0.5, marginLeft: 4 }}>{counts.done}</span>
          </button>
        </div>
      </div>

      <form onSubmit={submit} className="mc-bd-input">
        <input
          ref={inputRef}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          placeholder={kind === 'idea' ? 'New idea…' : 'Zip it out of your head…'}
        />
        <button type="button"
          onClick={() => setKind(kind === 'idea' ? 'dump' : 'idea')}
          title={`Saving as: ${kind === 'idea' ? 'idea' : 'zip'}. Click to switch.`}
          style={{
            appearance: 'none', cursor: 'pointer',
            border: '1px solid',
            background: kind === 'idea' ? 'var(--magenta-50)' : 'var(--bg)',
            color: kind === 'idea' ? 'var(--magenta-700)' : 'var(--fg-2)',
            borderColor: kind === 'idea' ? 'var(--magenta-300)' : 'var(--border)',
            borderRadius: 'var(--radius-md)', padding: '10px 12px',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
          }}>
          {kind === 'idea' ? <Icons.Lightbulb size={14}/> : <Icons.Brain size={14}/>}
          {kind === 'idea' ? 'idea' : 'zip'}
        </button>
        <button type="submit" className="mc-iconbtn"
          style={{ background: 'var(--indigo-500)', color: '#fff', width: 38, height: 38, borderRadius: 'var(--radius-md)' }}>
          <Icons.Plus size={16} sw={2.5}/>
        </button>
      </form>

      <div className="mc-bd-list">
        {items.length === 0 && (
          <div className="mc-bd-hint">
            {tab === 'done'
              ? 'Nothing checked off yet.'
              : 'Empty. Capture now, sort later — ↵ saves.'}
          </div>
        )}
        {items.map((b) => {
          const age = relTime(b.at);
          return (
            <div key={b.id} className={`mc-bd-item ${b.kind === 'idea' ? 'idea' : ''} ${b.flagged ? 'flagged' : ''} ${b.done ? 'is-done' : ''}`}>
              <span className="mc-bd-check" onClick={() => toggleBrainDone(b.id)}
                    title={b.done ? 'Mark as not done' : 'Mark as done'}>
                {b.done && <Icons.Check size={11} sw={3}/>}
              </span>
              <span className="mc-bd-kind">
                {b.kind === 'idea' ? <Icons.Lightbulb size={13}/> : <Icons.Brain size={13}/>}
              </span>
              <span className="text">{b.text}</span>
              <span className="age">{age}</span>
              <div className="mc-bd-item-actions">
                <button className={`mc-iconbtn ${b.flagged ? 'flagged-on' : ''}`}
                  title={b.flagged ? 'Unflag' : 'Flag as important'}
                  onClick={() => toggleBrainFlag(b.id)}>
                  <Icons.Bang size={14}/>
                </button>
                <button className="mc-iconbtn"
                  disabled={promoteDisabled}
                  title={promoteDisabled ? '4 priorities already — finish one first' : 'Promote to a weekly priority'}
                  onClick={() => promoteBrainItem(b.id)}>
                  <Icons.Target size={14}/>
                </button>
                <button className="mc-iconbtn danger" title="Discard" onClick={() => deleteBrainItem(b.id)}>
                  <Icons.X size={14}/>
                </button>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ fontSize: 11, color: 'var(--fg-3)', borderTop: '1px dashed var(--border)', paddingTop: 10,
        display: 'flex', justifyContent: 'space-between' }}>
        <span>{counts.all} active · {counts.idea} ideas · {counts.done} done</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <Icons.Bang size={11}/> = priority
        </span>
      </div>
    </section>
  );
}

function relTime(iso) {
  const then = new Date(iso);
  const now = new Date();
  const days = Math.floor((now - then) / 86400000);
  if (days <= 0) return 'today';
  if (days === 1) return '1d';
  if (days < 7) return days + 'd';
  if (days < 30) return Math.floor(days / 7) + 'w';
  return Math.floor(days / 30) + 'mo';
}

Object.assign(window, { BrainDump });
