/* global React, Icon, IconBtn, db, useSendTo, TOGGLEABLE_TOOLS */
const { useState, useEffect, useMemo, useCallback, useRef } = React;

// ============================================================
// Catalog — discovery surface for the tool library.
//
// The catalog is more than a settings page: it's the place where
// users find tools they didn't know they wanted. Three surfaces
// share that job:
//   1. Starter packs   — one-click bundles for common user types
//   2. Mood clusters   — moments in a day (Learn / Focus / Calm / Play / Utility)
//   3. Tool cards      — with related tools to chain discovery
// ============================================================

// ------------------------------------------------------------
// Mood metadata — overlays the engineering categories in
// TOGGLEABLE_TOOLS with user-facing "what's this for" framing.
// ------------------------------------------------------------
const MOODS = [
  {
    id: 'learn',
    label: 'Learn',
    tagline: 'Build knowledge that sticks',
    blurb: 'Drills, repetition, reflection — anything that grows what you know.',
    icon: 'school',
    accent: 'hsl(212, 85%, 60%)',
    tint:   'hsla(212, 85%, 60%, 0.10)',
  },
  {
    id: 'focus',
    label: 'Focus',
    tagline: 'Get the right work done',
    blurb: 'Capture what to do, track what you did, keep the noise out.',
    icon: 'target',
    accent: 'hsl(258, 70%, 65%)',
    tint:   'hsla(258, 70%, 65%, 0.10)',
  },
  {
    id: 'calm',
    label: 'Calm',
    tagline: 'A quieter moment in the day',
    blurb: 'Slow rituals, end-of-day check-ins, a place to think out loud.',
    icon: 'spa',
    accent: 'hsl(168, 60%, 50%)',
    tint:   'hsla(168, 60%, 50%, 0.10)',
  },
  {
    id: 'play',
    label: 'Play',
    tagline: 'Three minutes of nothing-in-particular',
    blurb: 'Coffee-break games. No streaks, no points to chase.',
    icon: 'sports_esports',
    accent: 'hsl(28, 90%, 60%)',
    tint:   'hsla(28, 90%, 60%, 0.10)',
  },
  {
    id: 'utility',
    label: 'Utility',
    tagline: 'The tiny tool you needed five minutes ago',
    blurb: 'Conversions, generators, viewers, decoders — quick in, quick out.',
    icon: 'build',
    accent: 'hsl(330, 65%, 60%)',
    tint:   'hsla(330, 65%, 60%, 0.10)',
  },
];
const MOOD_BY_ID = Object.fromEntries(MOODS.map(m => [m.id, m]));

// Per-tool overlay: mood + moment-of-day copy + related tools.
// If a tool is missing here, it defaults to mood='utility' with no
// extras — keeps the catalog from breaking when someone adds a new tool.
const TOOL_OVERLAY = {
  todo:      { mood: 'focus',   moment: 'Start of the day · between meetings',     related: ['note', 'journal', 'pomodoro'] },
  note:      { mood: 'focus',   moment: 'Mid-conversation · idea capture',         related: ['todo', 'journal', 'bookmark'] },
  bookmark:  { mood: 'focus',   moment: 'Reading · researching',                   related: ['note'] },
  pomodoro:  { mood: 'focus',   moment: 'Deep-work blocks · 25 minutes at a time', related: ['todo', 'journal'] },
  timetracker: { mood: 'focus', moment: 'Clocking in on a task · Friday “where did the week go?”', related: ['todo', 'pomodoro', 'journal'] },

  flashcard: { mood: 'learn',   moment: 'Mornings · commutes · waiting in line',   related: ['journal', 'note'] },
  journal:   { mood: 'calm',    moment: 'End of the day · Sunday evenings',        related: ['note', 'flashcard'] },

  tetris:    { mood: 'play',    moment: 'Coffee break · 3 minutes between tasks',  related: [] },

  json:      { mood: 'utility', moment: 'Debugging an API response',               related: ['diff', 'regex', 'convert'] },
  diff:      { mood: 'utility', moment: 'Reviewing changes · spotting typos',      related: ['json', 'regex'] },
  encode:    { mood: 'utility', moment: 'JWT debugging · URL params',              related: ['json', 'regex'] },
  regex:     { mood: 'utility', moment: 'Writing a pattern that almost works',     related: ['encode', 'diff'] },
  cron:      { mood: 'utility', moment: 'Setting up a scheduled job',              related: ['convert'] },
  color:     { mood: 'utility', moment: 'Picking a UI accent · checking contrast', related: ['convert'] },
  convert:   { mood: 'utility', moment: 'JSON → YAML · timestamps · units',        related: ['json', 'encode', 'color'] },
  password:  { mood: 'utility', moment: 'Signing up · rotating creds',             related: ['encode', 'totp'] },
  totp:      { mood: 'utility', moment: 'Logging in with two-factor auth',          related: ['password', 'encode', 'qr'] },
  calculator:{ mood: 'utility', moment: 'Splitting the bill · quick numbers',      related: ['convert'] },
  scratchpad:{ mood: 'utility', moment: 'Pasting text you\u2019ll process in a sec',     related: ['note', 'json'] },
  worldclock:{ mood: 'utility', moment: 'Scheduling across timezones',             related: ['cron', 'convert'] },
  qr:        { mood: 'utility', moment: 'Sharing a link · joining Wi-Fi',          related: ['encode', 'convert'] },
  image:     { mood: 'utility', moment: 'Converting a screenshot · shrinking an upload', related: ['color', 'qr', 'encode'] },
  habits:    { mood: 'focus',   moment: 'Same time, every day \u2014 a tiny habit',     related: ['todo', 'journal', 'mood'] },
  mood:      { mood: 'calm',    moment: 'One check-in before bed',                related: ['journal', 'habits'] },
  breathing: { mood: 'calm',    moment: 'Before a meeting \u00b7 before sleep',          related: ['mood', 'journal'] },
  g2048:     { mood: 'play',    moment: 'A quiet five minutes',                   related: ['tetris', 'minesweeper'] },
  minesweeper:{ mood: 'play',   moment: 'Lunch break \u00b7 idle hands',                 related: ['tetris', 'g2048'] },
  reading:   { mood: 'learn',   moment: 'Choosing your next book \u00b7 logging finished',related: ['flashcard', 'journal'] },
  writer:    { mood: 'focus',   moment: 'Morning pages \u00b7 the first draft',          related: ['note', 'journal', 'pomodoro'] },
  wordsearch:{ mood: 'play',    moment: 'Wind down \u00b7 break from screens',            related: ['tetris', 'minesweeper', 'g2048'] },
  sudoku:    { mood: 'play',    moment: 'A 10-minute logic warmup',               related: ['minesweeper', 'wordsearch'] },
  solitaire: { mood: 'play',    moment: 'A long quiet sit',                       related: ['tetris', 'sudoku'] },
  ambient:   { mood: 'calm',    moment: 'Focus background \u00b7 falling asleep',         related: ['breathing', 'pomodoro'] },

  keytest:     { mood: 'utility', moment: 'New keyboard \u00b7 a key feels dead',           related: ['mictest', 'camtest', 'refreshrate'] },
  mictest:     { mood: 'utility', moment: 'Before a call \u00b7 setting up a headset',       related: ['camtest', 'keytest', 'refreshrate'] },
  camtest:     { mood: 'utility', moment: 'Before a meeting \u00b7 testing a new webcam',    related: ['mictest', 'keytest', 'refreshrate'] },
  refreshrate: { mood: 'utility', moment: 'New monitor \u00b7 checking 120/144Hz',          related: ['camtest', 'keytest', 'mictest'] },
};

// ------------------------------------------------------------
// Starter packs — curated bundles for cold-start.
// `tools` is the EXACT set of toolIds enabled when the user picks
// this pack. Picking a pack does NOT disable other tools that
// are already on — it's additive.
// ------------------------------------------------------------
const STARTER_PACKS = [
  {
    id: 'student',
    label: 'Student starter',
    blurb: 'Drill what you study, write down what you think, ship what you owe.',
    icon: 'school',
    accent: 'hsl(212, 85%, 60%)',
    tools: ['flashcard', 'journal', 'todo', 'note', 'pomodoro', 'reading', 'writer'],
  },
  {
    id: 'daily-driver',
    label: 'Daily driver',
    blurb: 'A clean little workspace: tasks, notes, links, a place to vent.',
    icon: 'today',
    accent: 'hsl(258, 70%, 65%)',
    tools: ['todo', 'note', 'bookmark', 'journal', 'password', 'pomodoro', 'habits', 'calculator', 'timetracker'],
  },
  {
    id: 'dev-toolkit',
    label: 'Developer toolkit',
    blurb: 'The seven tabs you keep open in a browser, in one place.',
    icon: 'terminal',
    accent: 'hsl(168, 60%, 50%)',
    tools: ['json', 'diff', 'encode', 'totp', 'regex', 'cron', 'color', 'convert', 'qr', 'image', 'scratchpad'],
  },
  {
    id: 'just-for-fun',
    label: 'Just for fun',
    blurb: 'A coffee break, a sketch pad, a few useful odds and ends.',
    icon: 'celebration',
    accent: 'hsl(28, 90%, 60%)',
    tools: ['tetris', 'g2048', 'minesweeper', 'wordsearch', 'sudoku', 'solitaire'],
  },
  {
    id: 'calm-mind',
    label: 'Calm mind',
    blurb: 'End-of-day reflection without the productivity guilt trip.',
    icon: 'spa',
    accent: 'hsl(330, 65%, 60%)',
    tools: ['journal', 'note', 'mood', 'breathing', 'ambient', 'flashcard'],
  },
  {
    id: 'hardware-check',
    label: 'Hardware checkup',
    blurb: 'New machine, new desk setup? Test the keys, mic, camera and screen in a minute.',
    icon: 'memory',
    accent: 'hsl(195, 75%, 55%)',
    tools: ['keytest', 'mictest', 'camtest', 'refreshrate'],
  },
];

// ------------------------------------------------------------
// Helpers
// ------------------------------------------------------------
function overlayFor(toolId) {
  return TOOL_OVERLAY[toolId] || { mood: 'utility', moment: '', related: [] };
}
function moodFor(toolId) {
  return MOOD_BY_ID[overlayFor(toolId).mood] || MOOD_BY_ID.utility;
}

// ============================================================
// CatalogTool — main entry
// ============================================================
function CatalogTool() {
  const { send, isToolEnabled } = useSendTo();
  const [search, setSearch] = useState('');
  const [activeMood, setActiveMood] = useState('all'); // 'all' | mood id
  const [settings, setSettings] = useState({ disabledTools: [] });
  const [expandedId, setExpandedId] = useState(null);

  // Subscribe to settings — same pattern as the original catalog
  useEffect(() => {
    let mounted = true;
    const load = () => db.kv.get('settings').then(rec => {
      if (mounted && rec?.v) setSettings(rec.v);
    });
    load();
    const unsub = db.subscribe(({ store, value }) => {
      if (store === 'kv' && (value?.k === 'settings' || value === undefined)) load();
    });
    return () => { mounted = false; unsub(); };
  }, []);

  const disabled = settings.disabledTools || [];
  const isOn = useCallback((id) => !disabled.includes(id), [disabled]);

  const setDisabled = useCallback((nextDisabled) => {
    const next = { ...settings, disabledTools: nextDisabled };
    db.kv.put({ k: 'settings', v: next });
    setSettings(next);
  }, [settings]);

  const toggleTool = useCallback((id) => {
    const next = isOn(id) ? [...disabled, id] : disabled.filter(x => x !== id);
    setDisabled(next);
  }, [isOn, disabled, setDisabled]);

  const enablePack = useCallback((pack) => {
    // Remove every tool the pack covers from the disabled list.
    const next = disabled.filter(id => !pack.tools.includes(id));
    setDisabled(next);
  }, [disabled, setDisabled]);

  const open = useCallback((id) => {
    if (!isToolEnabled || isToolEnabled(id)) send(id, null);
  }, [isToolEnabled, send]);

  // ---- Derived data ----
  const tools = TOGGLEABLE_TOOLS;
  const enabledCount = tools.filter(t => isOn(t.id)).length;

  // Search lives across name, desc, mood label, moment copy, and category.
  // It short-circuits the mood filter so a search of "json" surfaces
  // matches regardless of the active mood tab.
  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return tools.filter(t => {
      const ov = overlayFor(t.id);
      const mood = MOOD_BY_ID[ov.mood];
      if (!q && activeMood !== 'all' && ov.mood !== activeMood) return false;
      if (!q) return true;
      return (
        t.label.toLowerCase().includes(q) ||
        t.desc.toLowerCase().includes(q) ||
        t.category.toLowerCase().includes(q) ||
        (mood?.label || '').toLowerCase().includes(q) ||
        (ov.moment || '').toLowerCase().includes(q)
      );
    });
  }, [tools, search, activeMood]);

  // Group filtered tools by mood for the sectioned grid.
  const grouped = useMemo(() => {
    const map = new Map();
    for (const t of filtered) {
      const moodId = overlayFor(t.id).mood;
      if (!map.has(moodId)) map.set(moodId, []);
      map.get(moodId).push(t);
    }
    // Preserve MOODS order
    return MOODS.filter(m => map.has(m.id)).map(m => [m, map.get(m.id)]);
  }, [filtered]);

  const moodCounts = useMemo(() => {
    const counts = { all: tools.length };
    for (const m of MOODS) counts[m.id] = 0;
    for (const t of tools) {
      const moodId = overlayFor(t.id).mood;
      counts[moodId] = (counts[moodId] || 0) + 1;
    }
    return counts;
  }, [tools]);

  return (
    <div className="cat2">
      {/* HERO */}
      <header className="cat2-hero">
        <div className="cat2-hero-text">
          <div className="cat2-eyebrow">Tool library</div>
          <h1 className="cat2-title">What do you want it to do today?</h1>
          <p className="cat2-sub">
            <strong>{enabledCount}</strong> of {tools.length} apps active.
            Pick a starter pack below, or browse {MOODS.length} moods to find something new.
          </p>
        </div>
        <div className="cat2-search">
          <Icon name="search" />
          <input
            placeholder="Search apps, moods, or moments…"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          {search && (
            <button className="cat2-search-clear" onClick={() => setSearch('')} title="Clear">
              <Icon name="close" />
            </button>
          )}
        </div>
      </header>

      {/* STARTER PACKS — hide while searching, since they'd be noise */}
      {!search && (
        <section className="cat2-block">
          <div className="cat2-block-head">
            <div>
              <h2>Starter packs</h2>
              <p>Pre-built bundles. One click turns on every app in the pack.</p>
            </div>
          </div>
          <div className="cat2-packs">
            {STARTER_PACKS.map(p => (
              <PackCard
                key={p.id}
                pack={p}
                isOn={isOn}
                tools={tools}
                onEnable={() => enablePack(p)}
                onOpenTool={open}
              />
            ))}
          </div>
        </section>
      )}

      {/* MOOD STRIP */}
      <section className="cat2-block">
        {!search && (
          <div className="cat2-block-head">
            <div>
              <h2>Browse by mood</h2>
              <p>Apps grouped by the moment in your day they're for.</p>
            </div>
          </div>
        )}
        <div className="cat2-mood-strip">
          <button
            className={`cat2-mood-pill ${activeMood === 'all' ? 'is-active' : ''}`}
            onClick={() => setActiveMood('all')}
          >
            <Icon name="apps" />
            <span>All</span>
            <em>{moodCounts.all}</em>
          </button>
          {MOODS.map(m => (
            <button
              key={m.id}
              className={`cat2-mood-pill ${activeMood === m.id ? 'is-active' : ''}`}
              onClick={() => setActiveMood(m.id)}
              style={activeMood === m.id ? { '--mood-accent': m.accent, '--mood-tint': m.tint } : { '--mood-accent': m.accent }}
            >
              <Icon name={m.icon} />
              <span>{m.label}</span>
              <em>{moodCounts[m.id] || 0}</em>
            </button>
          ))}
        </div>
      </section>

      {/* SECTIONED GRID */}
      {grouped.length === 0 ? (
        <div className="cat2-empty">
          <Icon name="search_off" />
          <div>
            <div className="title">No apps match</div>
            <div className="sub">Try a different search, or clear filters to see everything.</div>
          </div>
        </div>
      ) : grouped.map(([mood, items]) => (
        <MoodSection
          key={mood.id}
          mood={mood}
          tools={items}
          isOn={isOn}
          expandedId={expandedId}
          onExpand={setExpandedId}
          onOpen={open}
          onToggle={toggleTool}
        />
      ))}

      <SiteFooter />
    </div>
  );
}

// ============================================================
// PackCard — a starter-pack tile.
// Shows pack identity + which tools it covers + how many of those
// are already on. Enabling the pack turns ON every tool listed.
// ============================================================
const PACK_CHIP_LIMIT = 8; // keep every pack card a consistent height

function PackCard({ pack, isOn, tools, onEnable, onOpenTool }) {
  const byId = useMemo(() => Object.fromEntries(tools.map(t => [t.id, t])), [tools]);
  const packTools = pack.tools.map(id => byId[id]).filter(Boolean);
  const onCount = packTools.filter(t => isOn(t.id)).length;
  const allOn = onCount === packTools.length && packTools.length > 0;
  const shownTools = packTools.slice(0, PACK_CHIP_LIMIT);
  const overflow = packTools.length - shownTools.length;

  return (
    <div
      className={`cat2-pack ${allOn ? 'is-all-on' : ''}`}
      style={{ '--pack-accent': pack.accent, '--pack-tint': pack.accent.replace('60%)', '60%, 0.12)').replace('hsl(', 'hsla(') }}
    >
      <div className="cat2-pack-head">
        <div className="cat2-pack-icon">
          <Icon name={pack.icon} />
        </div>
        <div className="cat2-pack-progress">
          <span className="cat2-pack-progress-fill" style={{ width: `${(onCount / Math.max(1, packTools.length)) * 100}%` }} />
        </div>
      </div>
      <div className="cat2-pack-body">
        <div className="cat2-pack-name">{pack.label}</div>
        <div className="cat2-pack-blurb">{pack.blurb}</div>
      </div>
      <div className="cat2-pack-tools">
        {shownTools.map(t => (
          <button
            key={t.id}
            className={`cat2-pack-chip ${isOn(t.id) ? 'is-on' : 'is-off'}`}
            onClick={() => onOpenTool(t.id)}
            title={isOn(t.id) ? `Open ${t.label}` : `${t.label} is currently off`}
          >
            <Icon name={t.icon} />
            <span>{t.label}</span>
          </button>
        ))}
        {overflow > 0 && (
          <span className="cat2-pack-chip is-more" title={packTools.slice(PACK_CHIP_LIMIT).map(t => t.label).join(', ')}>
            +{overflow} more
          </span>
        )}
      </div>
      <div className="cat2-pack-foot">
        <div className="cat2-pack-counter">
          <strong>{onCount}</strong> / {packTools.length} active
        </div>
        {allOn ? (
          <button className="lh-btn ghost" disabled>
            <Icon name="check_circle" />All on
          </button>
        ) : (
          <button className="cat2-pack-enable" onClick={onEnable}>
            <Icon name="bolt" />Enable pack
          </button>
        )}
      </div>
    </div>
  );
}

// ============================================================
// MoodSection — one mood band: header + tool grid.
// ============================================================
function MoodSection({ mood, tools, isOn, expandedId, onExpand, onOpen, onToggle }) {
  return (
    <section
      className="cat2-mood-section"
      style={{ '--mood-accent': mood.accent, '--mood-tint': mood.tint }}
    >
      <div className="cat2-mood-section-head">
        <div className="cat2-mood-section-icon">
          <Icon name={mood.icon} />
        </div>
        <div className="cat2-mood-section-text">
          <h2>{mood.label} <span className="cat2-mood-section-tag">{mood.tagline}</span></h2>
          <p>{mood.blurb}</p>
        </div>
        <div className="cat2-mood-section-count">
          {tools.length} {tools.length === 1 ? 'app' : 'apps'}
        </div>
      </div>
      <div className="cat2-grid">
        {tools.map(t => (
          <ToolCard
            key={t.id}
            tool={t}
            mood={mood}
            on={isOn(t.id)}
            expanded={expandedId === t.id}
            onExpand={() => onExpand(expandedId === t.id ? null : t.id)}
            onOpen={() => onOpen(t.id)}
            onToggle={() => onToggle(t.id)}
            relatedTools={overlayFor(t.id).related
              .map(id => TOGGLEABLE_TOOLS.find(x => x.id === id))
              .filter(Boolean)}
          />
        ))}
      </div>
    </section>
  );
}

// ============================================================
// ToolCard — richer than v1.
// Front: icon + name + moment-of-day · status badge · primary action
// Back (expanded): description + related tools + secondary actions
// ============================================================
function ToolCard({ tool, mood, on, expanded, onExpand, onOpen, onToggle, relatedTools }) {
  const ov = overlayFor(tool.id);
  return (
    <div className={`cat2-card ${on ? 'is-on' : 'is-off'} ${expanded ? 'is-expanded' : ''}`}>
      <button className="cat2-card-main" onClick={onExpand}>
        <div className="cat2-card-icon">
          <Icon name={tool.icon} />
        </div>
        <div className="cat2-card-body">
          <div className="cat2-card-row">
            <span className="cat2-card-name">{tool.label}</span>
            <span className={`cat2-card-pill ${on ? 'on' : 'off'}`}>
              <span className="cat2-card-pill-dot" />
              {on ? 'On' : 'Off'}
            </span>
          </div>
          {ov.moment ? (
            <div className="cat2-card-moment">
              <Icon name="schedule" />
              <span>{ov.moment}</span>
            </div>
          ) : (
            <div className="cat2-card-moment cat2-card-moment-faint">
              <span>{tool.category}</span>
            </div>
          )}
        </div>
        <Icon name={expanded ? 'expand_less' : 'expand_more'} className="cat2-card-chevron" />
      </button>

      {expanded && (
        <div className="cat2-card-drawer">
          <p className="cat2-card-desc">{tool.desc}</p>

          {relatedTools.length > 0 && (
            <div className="cat2-card-related">
              <div className="cat2-card-related-label">Often used with</div>
              <div className="cat2-card-related-chips">
                {relatedTools.map(rt => (
                  <span key={rt.id} className="cat2-card-related-chip">
                    <Icon name={rt.icon} />{rt.label}
                  </span>
                ))}
              </div>
            </div>
          )}

          <div className="cat2-card-actions">
            {on ? (
              <>
                <button className="lh-btn primary" onClick={(e) => { e.stopPropagation(); onOpen(); }}>
                  <Icon name="arrow_forward" />Open {tool.label}
                </button>
                <button className="lh-btn ghost" onClick={(e) => { e.stopPropagation(); onToggle(); }} title="Turn off">
                  <Icon name="visibility_off" />Turn off
                </button>
              </>
            ) : (
              <button className="lh-btn primary" onClick={(e) => { e.stopPropagation(); onToggle(); }}>
                <Icon name="power_settings_new" />Turn on
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

window.CatalogTool = CatalogTool;
// Expose mood + pack registries so other tools (onboarding, home) can reuse them.
Object.assign(window, { CATALOG_MOODS: MOODS, CATALOG_PACKS: STARTER_PACKS, CATALOG_TOOL_OVERLAY: TOOL_OVERLAY });
