// Board screen — todos, shopping, notes with richer overview content

const SHOP_CATS = ['general', 'produce', 'dairy', 'meat', 'bakery', 'drinks', 'snacks', 'household', 'hygiene'];
const TODO_TEMPLATES = ['Take bins out', 'Review family calendar', 'Water the plants', 'Pay utility bill'];
const SHOP_TEMPLATES = [
  { text: 'Milk', qty: '1', cat: 'dairy' },
  { text: 'Eggs', qty: '12', cat: 'dairy' },
  { text: 'Bread', qty: '1', cat: 'bakery' },
  { text: 'Sparkling water', qty: '6', cat: 'drinks' },
];
const NOTE_PROMPTS = [
  { label: 'Weekend plan', content: 'Weekend plan\n- Saturday\n- Sunday', color: '#F0DCA8' },
  { label: 'Dinner ideas', content: 'Dinner ideas\n- Monday\n- Tuesday\n- Wednesday', color: '#D4EAF4' },
  { label: 'House note', content: 'House note\nRemember to...', color: '#D4F4E0' },
  { label: 'Family message', content: 'Family message\nQuick update for everyone:', color: '#F0C9B8' },
];

function titleCase(value) {
  return String(value || '')
    .split(/[_\s-]+/)
    .filter(Boolean)
    .map(part => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');
}

function boardTone(sub) {
  if (sub === 'shopping') return { accent: '#6E8662', soft: '#EDF1E9' };
  if (sub === 'notes') return { accent: '#8D6F57', soft: '#F3EADF' };
  return { accent: '#C9562E', soft: '#F5E7DF' };
}

function ListsScreen({ store, cfg, user }) {
  const [sub, setSub] = React.useState('todos');
  const [input, setInput] = React.useState('');
  const [shopQty, setShopQty] = React.useState('');
  const [shopCat, setShopCat] = React.useState('general');
  const tone = boardTone(sub);

  const handleAdd = () => {
    if (!input.trim()) return;
    if (sub === 'todos') store.addTodo(input);
    else if (sub === 'shopping') store.addShop(input, shopQty, shopCat);
    setInput('');
    setShopQty('');
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <TopBar
        title="Board"
        subtitle="Shared household"
        trailing={<BoardTrailingBadge sub={sub} store={store} tone={tone} />}
      />

      <div style={{ padding: '0 20px 10px' }}>
        <div style={{ background: 'var(--hh-surface-2)', borderRadius: 999, padding: 3, display: 'flex' }}>
          {[['todos', 'Todos'], ['shopping', 'Shopping'], ['notes', 'Notes']].map(([id, label]) => (
            <button
              key={id}
              onClick={() => setSub(id)}
              className="press"
              style={{
                flex: 1,
                padding: '9px 6px',
                borderRadius: 999,
                fontSize: 13,
                fontWeight: 600,
                background: sub === id ? 'var(--hh-surface)' : 'transparent',
                color: sub === id ? 'var(--hh-ink)' : 'var(--hh-ink-mute)',
                boxShadow: sub === id ? 'var(--hh-shadow-sm)' : 'none',
              }}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      <div className="hh-scroll" style={{ flex: 1, overflow: 'auto', paddingBottom: 12 }}>
        {sub === 'todos' && <TodosList store={store} user={user} tone={tone} />}
        {sub === 'shopping' && <ShoppingList store={store} tone={tone} />}
        {sub === 'notes' && <NotesList store={store} tone={tone} />}
      </div>

      {sub === 'todos' && (
        <div style={{ padding: '10px 16px calc(12px + var(--hh-tabbar-h) + env(safe-area-inset-bottom))', display: 'flex', gap: 8, background: 'var(--hh-bg)', borderTop: '1px solid var(--hh-line-soft)' }}>
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, background: 'var(--hh-surface)', borderRadius: 16, padding: '0 14px', height: 44, border: '1px solid var(--hh-line-soft)' }}>
            <input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleAdd()}
              placeholder="Add a todo..."
              style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 14, color: 'var(--hh-ink)' }}
            />
          </div>
          <button onClick={handleAdd} className="press hh-btn accent" style={{ height: 44, width: 44, padding: 0, borderRadius: 999 }}>
            <Icon name="plus" size={18} color="#fff" />
          </button>
        </div>
      )}

      {sub === 'shopping' && (
        <div style={{ padding: '10px 16px calc(12px + var(--hh-tabbar-h) + env(safe-area-inset-bottom))', background: 'var(--hh-bg)', borderTop: '1px solid var(--hh-line-soft)', display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ display: 'flex', gap: 6 }}>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, background: 'var(--hh-surface)', borderRadius: 16, padding: '0 12px', height: 44, border: '1px solid var(--hh-line-soft)' }}>
              <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleAdd()}
                placeholder="Add item..."
                style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 14, color: 'var(--hh-ink)' }}
              />
            </div>
            <input value={shopQty} onChange={(e) => setShopQty(e.target.value)} placeholder="Qty" style={{ width: 52, height: 44, borderRadius: 12, border: '1px solid var(--hh-line-soft)', background: 'var(--hh-surface)', padding: '0 8px', fontSize: 13, color: 'var(--hh-ink)', outline: 'none' }} />
            <select value={shopCat} onChange={(e) => setShopCat(e.target.value)} style={{ height: 44, borderRadius: 12, border: '1px solid var(--hh-line-soft)', background: 'var(--hh-surface)', padding: '0 6px', fontSize: 12, color: 'var(--hh-ink)', outline: 'none' }}>
              {SHOP_CATS.map(cat => <option key={cat} value={cat}>{titleCase(cat)}</option>)}
            </select>
            <button onClick={handleAdd} className="press hh-btn accent" style={{ height: 44, width: 44, padding: 0, borderRadius: 999 }}>
              <Icon name="plus" size={18} color="#fff" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function BoardTrailingBadge({ sub, store, tone }) {
  const config = sub === 'shopping'
    ? { icon: 'cart', value: store.shopping.filter(item => !item.done).length }
    : sub === 'notes'
      ? { icon: 'note', value: store.notes.length }
      : { icon: 'check', value: store.todos.filter(todo => !todo.done).length };

  return (
    <div style={{ width: 44, height: 44, borderRadius: 999, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', boxShadow: 'var(--hh-shadow-sm)' }}>
      <Icon name={config.icon} size={18} color={tone.accent} />
      <div style={{ position: 'absolute', top: -2, right: -2, minWidth: 18, height: 18, borderRadius: 999, padding: '0 4px', background: tone.accent, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700 }}>
        {config.value}
      </div>
    </div>
  );
}

function BoardHero({ eyebrow, title, body, icon, tone, stats, actions }) {
  return (
    <div style={{ padding: '0 20px 14px' }}>
      <div style={{ borderRadius: 24, overflow: 'hidden', padding: 18, background: `linear-gradient(135deg, ${tone.soft}, rgba(255,255,255,0.92))`, border: `1px solid ${tone.accent}26`, boxShadow: '0 12px 32px rgba(42,33,26,0.06)' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', justifyContent: 'space-between' }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: tone.accent, fontWeight: 700 }}>{eyebrow}</div>
            <div className="hh-serif" style={{ fontSize: 30, lineHeight: 1, color: 'var(--hh-ink)', marginTop: 8 }}>{title}</div>
            <div style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--hh-ink-mute)', marginTop: 8 }}>{body}</div>
          </div>
          <div style={{ width: 50, height: 50, flexShrink: 0, borderRadius: 18, background: '#fff', border: `1px solid ${tone.accent}22`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name={icon} size={22} color={tone.accent} />
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 14 }}>
          {stats.map(stat => (
            <div key={stat.label} style={{ background: 'rgba(255,255,255,0.82)', border: '1px solid rgba(42,33,26,0.06)', borderRadius: 18, padding: '10px 12px' }}>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{stat.label}</div>
              <div style={{ fontSize: 22, lineHeight: 1, fontWeight: 700, color: 'var(--hh-ink)', marginTop: 5 }}>{stat.value}</div>
            </div>
          ))}
        </div>

        {actions && actions.length > 0 && (
          <div className="hh-hscroll hh-scroll" style={{ marginTop: 12, padding: 0 }}>
            <div style={{ display: 'flex', gap: 8 }}>
              {actions.map(action => (
                <button key={action.label} onClick={action.onClick} className="press" style={{ height: 34, padding: '0 12px', borderRadius: 999, border: `1px solid ${tone.accent}26`, background: '#fff', color: 'var(--hh-ink)', fontSize: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
                  {action.icon && <Icon name={action.icon} size={14} color={tone.accent} />}
                  {action.label}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function SectionRow({ title, detail, action }) {
  return (
    <div style={{ padding: '0 20px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
      <div>
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--hh-ink)' }}>{title}</div>
        {detail && <div style={{ fontSize: 12, color: 'var(--hh-ink-mute)', marginTop: 2 }}>{detail}</div>}
      </div>
      {action}
    </div>
  );
}

function EmptyStateCard({ icon, title, body, tone, children }) {
  return (
    <div style={{ padding: '0 20px 14px' }}>
      <div className="hh-card" style={{ padding: 18, borderRadius: 22, background: `linear-gradient(180deg, ${tone.soft}, rgba(255,255,255,0.86))`, border: `1px solid ${tone.accent}18` }}>
        <div style={{ width: 42, height: 42, borderRadius: 14, background: '#fff', border: `1px solid ${tone.accent}20`, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
          <Icon name={icon} size={18} color={tone.accent} />
        </div>
        <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--hh-ink)' }}>{title}</div>
        <div style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--hh-ink-mute)', marginTop: 6 }}>{body}</div>
        {children && <div style={{ marginTop: 12 }}>{children}</div>}
      </div>
    </div>
  );
}

function TodosList({ store, user, tone }) {
  const [filter, setFilter] = React.useState('all');
  const [showForm, setShowForm] = React.useState(false);
  const [draft, setDraft] = React.useState({ title: '', assignee: '', dueDate: '' });
  const { todos, family } = store;
  const mineName = (user?.name || '').toLowerCase();
  const active = todos.filter(todo => !todo.done);
  const mine = active.filter(todo => (todo.assign || '').toLowerCase() === mineName);
  const done = todos.filter(todo => todo.done);
  const filtered = filter === 'done' ? done : filter === 'mine' ? mine : active;
  const spotlight = active.slice(0, 3);

  const handleAddFull = (e) => {
    e.preventDefault();
    if (!draft.title.trim()) return;
    store.addTodo(draft.title, draft.assignee || undefined, draft.dueDate || undefined);
    setDraft({ title: '', assignee: '', dueDate: '' });
    setShowForm(false);
  };

  return (
    <div>
      <BoardHero
        eyebrow="Today"
        title={active.length ? `${active.length} tasks in motion` : 'A calm board'}
        body={active.length ? 'Keep momentum with a short focus list for the house.' : 'Start with a couple of small wins and the board stays useful all day.'}
        icon="check"
        tone={tone}
        stats={[
          { label: 'Open', value: active.length },
          { label: 'Mine', value: mine.length },
          { label: 'Done', value: done.length },
        ]}
        actions={TODO_TEMPLATES.map(text => ({ label: text, icon: 'plus', onClick: () => store.addTodo(text) }))}
      />

      <SectionRow
        title="Task lanes"
        detail={filter === 'done' ? 'Completed items stay here until removed.' : 'Switch perspective without losing the shared context.'}
        action={
          <button onClick={() => setShowForm(v => !v)} className="press" style={{ width: 34, height: 34, borderRadius: 999, background: showForm ? tone.accent : 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name={showForm ? 'close' : 'sparkle'} size={15} color={showForm ? '#fff' : tone.accent} />
          </button>
        }
      />

      <div style={{ padding: '0 20px 12px', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {[['all', 'Active'], ['mine', 'Mine'], ['done', 'Done']].map(([id, label]) => (
          <Chip key={id} active={filter === id} onClick={() => setFilter(id)} color={tone.accent}>{label}</Chip>
        ))}
      </div>

      {showForm && (
        <form onSubmit={handleAddFull} style={{ padding: '0 20px 14px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div className="hh-card" style={{ padding: 14, display: 'grid', gap: 8 }}>
            <input value={draft.title} onChange={(e) => setDraft(current => ({ ...current, title: e.target.value }))} placeholder="Task title..." required style={{ height: 42, borderRadius: 12, border: '1px solid var(--hh-line-soft)', padding: '0 12px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', fontSize: 14, outline: 'none' }} />
            <div style={{ display: 'flex', gap: 8 }}>
              <select value={draft.assignee} onChange={(e) => setDraft(current => ({ ...current, assignee: e.target.value }))} style={{ flex: 1, height: 40, borderRadius: 12, border: '1px solid var(--hh-line-soft)', padding: '0 8px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', fontSize: 13, outline: 'none' }}>
                <option value="">Anyone</option>
                {(family || []).map(member => <option key={member.id} value={member.name}>{member.name}</option>)}
              </select>
              <input type="date" value={draft.dueDate} onChange={(e) => setDraft(current => ({ ...current, dueDate: e.target.value }))} style={{ flex: 1, height: 40, borderRadius: 12, border: '1px solid var(--hh-line-soft)', padding: '0 8px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', fontSize: 13, outline: 'none' }} />
              <button type="submit" className="press hh-btn accent" style={{ height: 40, padding: '0 16px', flexShrink: 0 }}>Add</button>
            </div>
          </div>
        </form>
      )}

      {spotlight.length > 0 && filter !== 'done' && (
        <div style={{ padding: '0 20px 14px' }}>
          <div className="hh-card" style={{ padding: 14, display: 'grid', gap: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
              <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: tone.accent }}>Focus next</div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>Top {spotlight.length}</div>
            </div>
            {spotlight.map(todo => (
              <button key={todo.id} onClick={() => store.toggleTodo(todo.id)} className="press" style={{ width: '100%', textAlign: 'left', display: 'flex', gap: 10, alignItems: 'center', padding: '10px 12px', borderRadius: 16, background: 'var(--hh-surface-2)' }}>
                <div style={{ width: 10, height: 10, borderRadius: 999, background: tone.accent, flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--hh-ink)' }}>{todo.text}</div>
                  <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)', marginTop: 3 }}>{[todo.due, todo.assign].filter(Boolean).join(' · ') || 'Tap to mark complete'}</div>
                </div>
                <Icon name="check" size={14} color="var(--hh-ink-mute)" />
              </button>
            ))}
          </div>
        </div>
      )}

      {filtered.length === 0 ? (
        <EmptyStateCard icon="sparkle" title={filter === 'done' ? 'Nothing completed yet' : 'No tasks in this lane'} body={filter === 'mine' ? 'Assign a task to yourself or claim one from the shared list.' : 'Use a quick template or add your own task below.'} tone={tone}>
          <div className="hh-hscroll hh-scroll" style={{ padding: 0 }}>
            <div style={{ display: 'flex', gap: 8 }}>
              {TODO_TEMPLATES.map(text => (
                <button key={text} onClick={() => store.addTodo(text)} className="press" style={{ height: 34, padding: '0 12px', borderRadius: 999, background: '#fff', border: `1px solid ${tone.accent}24`, color: 'var(--hh-ink)', fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap' }}>
                  {text}
                </button>
              ))}
            </div>
          </div>
        </EmptyStateCard>
      ) : (
        <div className="hh-card" style={{ margin: '0 20px' }}>
          {filtered.map((todo, index) => (
            <div key={todo.id} style={{ padding: '14px', display: 'flex', gap: 12, alignItems: 'center', borderBottom: index < filtered.length - 1 ? '1px solid var(--hh-line-soft)' : 'none' }}>
              <button onClick={() => store.toggleTodo(todo.id)} className="press" style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, border: `2px solid ${todo.done ? tone.accent : 'var(--hh-line)'}`, background: todo.done ? tone.accent : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {todo.done && <Icon name="check" size={12} color="#fff" />}
              </button>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, textDecoration: todo.done ? 'line-through' : 'none', color: todo.done ? 'var(--hh-ink-mute)' : 'var(--hh-ink)' }}>{todo.text}</div>
                <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)', marginTop: 2, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {todo.due && <span>{todo.due}</span>}
                  {todo.assign && <span>{todo.assign}</span>}
                </div>
              </div>
              <button onClick={() => store.removeTodo(todo.id)} className="press" style={{ width: 28, height: 28, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'transparent' }}>
                <Icon name="trash2" size={14} color="var(--hh-ink-mute)" />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ShoppingList({ store, tone }) {
  const { shopping } = store;
  const pending = shopping.filter(item => !item.done);
  const done = shopping.filter(item => item.done);
  const progress = shopping.length ? Math.round((done.length / shopping.length) * 100) : 0;
  const categories = [...new Set(pending.map(item => item.cat || 'general'))];

  return (
    <div>
      <BoardHero
        eyebrow="Shopping run"
        title={pending.length ? `${pending.length} items to pick up` : 'List is clear'}
        body={pending.length ? 'Group essentials by aisle so the next store trip feels lighter.' : 'Add staple items, prep a meal plan, or keep a standing pantry list.'}
        icon="cart"
        tone={tone}
        stats={[
          { label: 'To buy', value: pending.length },
          { label: 'Done', value: done.length },
          { label: 'Aisles', value: categories.length },
        ]}
        actions={SHOP_TEMPLATES.map(item => ({ label: item.text, icon: 'plus', onClick: () => store.addShop(item.text, item.qty, item.cat) }))}
      />

      <div style={{ padding: '0 20px 14px' }}>
        <div className="hh-card" style={{ padding: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: tone.accent }}>Completion</div>
              <div style={{ fontSize: 13, color: 'var(--hh-ink-mute)', marginTop: 4 }}>{shopping.length ? `${progress}% of the list is already picked up.` : 'Nothing on the list yet.'}</div>
            </div>
            {done.length > 0 && (
              <button className="press" onClick={() => store.clearShopDone()} style={{ fontSize: 12, color: tone.accent, padding: '6px 10px', borderRadius: 10, background: tone.soft, fontWeight: 700 }}>
                Clear {done.length}
              </button>
            )}
          </div>
          <div style={{ marginTop: 12, height: 8, borderRadius: 999, background: 'var(--hh-surface-2)', overflow: 'hidden' }}>
            <div style={{ width: `${progress}%`, height: '100%', background: tone.accent, borderRadius: 999 }} />
          </div>
        </div>
      </div>

      {pending.length === 0 ? (
        <EmptyStateCard icon="cart" title="Shopping list is empty" body="Keep the page useful with a few standing staples, then use the quick bar at the bottom for the rest." tone={tone}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {SHOP_TEMPLATES.map(item => (
              <button key={item.text} onClick={() => store.addShop(item.text, item.qty, item.cat)} className="press" style={{ minHeight: 44, borderRadius: 14, background: '#fff', border: `1px solid ${tone.accent}24`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 12px', color: 'var(--hh-ink)', fontSize: 13, fontWeight: 600 }}>
                <span>{item.text}</span>
                <span style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{item.qty}</span>
              </button>
            ))}
          </div>
        </EmptyStateCard>
      ) : (
        categories.map(cat => {
          const items = pending.filter(item => (item.cat || 'general') === cat);
          return (
            <div key={cat} style={{ paddingBottom: 12 }}>
              <SectionRow title={titleCase(cat)} detail={`${items.length} pending`} />
              <div className="hh-card" style={{ margin: '0 20px' }}>
                {items.map((item, index) => (
                  <div key={item.id} style={{ padding: '12px 14px', display: 'flex', gap: 12, alignItems: 'center', borderBottom: index < items.length - 1 ? '1px solid var(--hh-line-soft)' : 'none' }}>
                    <button onClick={() => store.toggleShop(item.id)} className="press" style={{ width: 22, height: 22, borderRadius: 6, flexShrink: 0, border: `2px solid ${tone.accent}`, background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--hh-ink)' }}>{item.text}</div>
                      <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)', marginTop: 2 }}>{item.added ? `Added by ${item.added}` : 'Ready to pick up'}</div>
                    </div>
                    {item.qty && <div className="hh-mono" style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>x{item.qty}</div>}
                    <button onClick={() => store.removeShop(item.id)} className="press" style={{ width: 28, height: 28, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'transparent' }}>
                      <Icon name="trash2" size={13} color="var(--hh-ink-mute)" />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          );
        })
      )}

      {done.length > 0 && (
        <div style={{ paddingBottom: 10 }}>
          <SectionRow title="Already in cart" detail={`${done.length} completed`} />
          <div className="hh-card" style={{ margin: '0 20px' }}>
            {done.map((item, index) => (
              <div key={item.id} style={{ padding: '12px 14px', display: 'flex', gap: 12, alignItems: 'center', borderBottom: index < done.length - 1 ? '1px solid var(--hh-line-soft)' : 'none' }}>
                <button onClick={() => store.toggleShop(item.id)} className="press" style={{ width: 22, height: 22, borderRadius: 6, flexShrink: 0, border: `2px solid ${tone.accent}`, background: tone.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="check" size={12} color="#fff" />
                </button>
                <div style={{ flex: 1, minWidth: 0, fontSize: 14, fontWeight: 600, textDecoration: 'line-through', color: 'var(--hh-ink-mute)' }}>{item.text}</div>
                {item.qty && <div className="hh-mono" style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>x{item.qty}</div>}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function NotesList({ store, tone }) {
  const { notes } = store;
  const [showForm, setShowForm] = React.useState(false);
  const [content, setContent] = React.useState('');
  const [color, setColor] = React.useState('#F0DCA8');
  const [editId, setEditId] = React.useState(null);
  const NOTE_COLORS = ['#F0DCA8', '#F0C9B8', '#CBDABB', '#C5D5DE', '#DCC7D5', '#F4D4D4', '#D4EAF4', '#D4F4E0'];
  const pinned = notes.filter(note => note.pinned);
  const rest = notes.filter(note => !note.pinned);

  const handleAdd = (e) => {
    e.preventDefault();
    if (!content.trim()) return;
    if (editId) store.updateNote(editId, content, color);
    else store.addNote(content, color);
    setContent('');
    setColor('#F0DCA8');
    setEditId(null);
    setShowForm(false);
  };

  const startEdit = (note) => {
    setEditId(note.id);
    setContent(note.title + (note.body ? `\n${note.body}` : ''));
    setColor(note.color);
    setShowForm(true);
  };

  const applyPrompt = (prompt) => {
    setEditId(null);
    setContent(prompt.content);
    setColor(prompt.color);
    setShowForm(true);
  };

  const renderNote = (note) => (
    <div key={note.id} className="press" onClick={() => startEdit(note)} style={{ background: note.color, borderRadius: 18, padding: 12, minHeight: 120, display: 'flex', flexDirection: 'column', position: 'relative', cursor: 'pointer', boxShadow: '0 8px 20px rgba(42,33,26,0.05)' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 8, gap: 4 }}>
        <div className="hh-serif" style={{ fontSize: 15, fontWeight: 700, color: '#2A211A', flex: 1 }}>{note.title}</div>
        <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
          <button onClick={(e) => { e.stopPropagation(); store.toggleNotePin(note.id); }} className="press" style={{ width: 24, height: 24, borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', background: note.pinned ? 'rgba(0,0,0,0.16)' : 'transparent' }}>
            <Icon name="pin" size={12} color="#2A211A" />
          </button>
          <button onClick={(e) => { e.stopPropagation(); store.removeNote(note.id); }} className="press" style={{ width: 24, height: 24, borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="trash2" size={12} color="#2A211A" />
          </button>
        </div>
      </div>
      {note.body && <div style={{ fontSize: 12, lineHeight: 1.45, color: '#2A211A', opacity: 0.78, whiteSpace: 'pre-line', flex: 1 }}>{note.body}</div>}
    </div>
  );

  return (
    <div style={{ paddingBottom: 20 }}>
      <BoardHero
        eyebrow="Capture"
        title={notes.length ? `${notes.length} shared notes` : 'Family memory wall'}
        body={notes.length ? 'Keep little updates, plans, and reminders where everyone can find them.' : 'Use short posts for plans, reminders, and warm household context.'}
        icon="note"
        tone={tone}
        stats={[
          { label: 'Pinned', value: pinned.length },
          { label: 'Notes', value: notes.length },
          { label: 'Colors', value: NOTE_COLORS.length },
        ]}
        actions={NOTE_PROMPTS.map(prompt => ({ label: prompt.label, icon: 'plus', onClick: () => applyPrompt(prompt) }))}
      />

      <SectionRow
        title="Compose"
        detail={editId ? 'Editing an existing note.' : 'Start from scratch or use a prompt above.'}
        action={
          <button onClick={() => { if (showForm && editId) { setEditId(null); setContent(''); setColor('#F0DCA8'); } setShowForm(v => !v); }} className="press hh-btn accent" style={{ height: 36, padding: '0 14px', gap: 6 }}>
            <Icon name="plus" size={14} color="#fff" />
            {showForm ? 'Close' : 'New note'}
          </button>
        }
      />

      {showForm && (
        <form onSubmit={handleAdd} style={{ padding: '0 16px 14px' }}>
          <div className="hh-card" style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <textarea value={content} onChange={(e) => setContent(e.target.value)} placeholder="Write a note for the family..." rows={4} required style={{ width: '100%', background: 'var(--hh-surface-2)', border: '1px solid var(--hh-line-soft)', borderRadius: 12, padding: 10, fontSize: 14, color: 'var(--hh-ink)', outline: 'none', resize: 'none', fontFamily: 'inherit' }} />
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
              {NOTE_COLORS.map(swatch => (
                <button key={swatch} type="button" onClick={() => setColor(swatch)} style={{ width: 24, height: 24, borderRadius: '50%', background: swatch, border: color === swatch ? '3px solid var(--hh-ink)' : '2px solid transparent', flexShrink: 0 }} />
              ))}
              <div style={{ flex: 1 }} />
              <button type="submit" className="press hh-btn accent" style={{ height: 36, padding: '0 14px' }}>{editId ? 'Update' : 'Post'}</button>
            </div>
          </div>
        </form>
      )}

      {notes.length === 0 && (
        <EmptyStateCard icon="note" title="No notes yet" body="Seed the board with one message, meal plan, or reminder so it feels lived in from the start." tone={tone}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {NOTE_PROMPTS.slice(0, 4).map(prompt => (
              <button key={prompt.label} onClick={() => applyPrompt(prompt)} className="press" style={{ minHeight: 50, borderRadius: 14, background: '#fff', border: `1px solid ${tone.accent}24`, padding: '0 12px', textAlign: 'left', fontSize: 13, fontWeight: 600, color: 'var(--hh-ink)' }}>
                {prompt.label}
              </button>
            ))}
          </div>
        </EmptyStateCard>
      )}

      {pinned.length > 0 && (
        <>
          <SectionRow title="Pinned" detail="Anchor the important context." />
          <div style={{ padding: '0 16px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {pinned.map(renderNote)}
          </div>
        </>
      )}

      {rest.length > 0 && (
        <>
          <SectionRow title="All notes" detail={`${rest.length} in the stack`} />
          <div style={{ padding: '0 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {rest.map(renderNote)}
          </div>
        </>
      )}
    </div>
  );
}

window.ListsScreen = ListsScreen;