// sheets.jsx — bottom-sheet UIs shared by the app. Uses window.Ico.
// Exposes window.Sheet, window.EmojiSheet, window.ItemSheet, window.ListSheet.
(function () {
const Ico = window.Ico;
const { useState: useS, useEffect: useE, useRef: useR } = React;

const glassFx = (t) =>
  (t.effects && t.effects.blur && t.effects.blur !== 'none')
    ? { backdropFilter: t.effects.blur, WebkitBackdropFilter: t.effects.blur }
    : {};

// ── generic bottom sheet shell ──────────────────────────────────────
function Sheet({ t, onClose, children, z = 50 }) {
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: z, display: 'flex', flexDirection: 'column',
      justifyContent: 'flex-end', background: 'rgba(4,7,12,.45)',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: t.color.surface, ...glassFx(t),
        borderTopLeftRadius: Math.max(18, t.radius.card), borderTopRightRadius: Math.max(18, t.radius.card),
        borderTop: t.glass ? `1px solid ${t.color.border}` : (t.mode === 'dark' ? `1px solid ${t.color.border}` : 'none'),
        boxShadow: t.shadow.pop, padding: '10px 16px 18px',
      }}>
        <div style={{ width: 38, height: 4, borderRadius: 2, background: t.color.checkRing, margin: '2px auto 12px' }} />
        {children}
      </div>
    </div>
  );
}

// ── emoji picker sheet ──────────────────────────────────────────────
function EmojiSheet({ t, locale, item, onPick, onClear, onClose }) {
  const L = window.I18N_T ? window.I18N_T(locale || 'en') : null;
  const tr = (k) => (L ? L.ui(k) : k);
  const trItem = (n) => (L ? L.item(n) : n);
  const [q, setQ] = useS('');
  useE(() => { setQ(''); }, [item && item.id]);
  if (!item) return null;
  const palette = window.EMOJI_PICKER || [];
  const idx = window.EMOJI_SEARCH || {};
  const query = q.trim().toLowerCase();
  const shown = query ? palette.filter((e) => (idx[e] || []).some((term) => term.includes(query))) : palette;
  return (
    <Sheet t={t} onClose={onClose} z={60}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <div style={{
          flex: '0 0 auto', width: 38, height: 38, borderRadius: t.radius.chip, background: t.color.surfaceAlt,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 21, lineHeight: 1,
        }}>
          {item.emoji || <span style={{ fontFamily: t.font.head, fontSize: 15, fontWeight: 700, color: t.color.textFaint }}>{(trItem(item.name).trim()[0] || '?').toUpperCase()}</span>}
        </div>
        <div style={{ flex: '1 1 auto', minWidth: 0 }}>
          <div style={{ fontFamily: t.font.head, fontSize: 15, fontWeight: 700, color: t.color.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{trItem(item.name)}</div>
          <div style={{ fontSize: 12, color: t.color.textFaint, marginTop: 1 }}>{tr('chooseIcon')}</div>
        </div>
        {item.emoji && (
          <button onClick={onClear} style={{
            flex: '0 0 auto', border: `1px solid ${t.color.border}`, background: 'transparent',
            color: t.color.textMuted, fontFamily: t.font.head, fontSize: 12.5, fontWeight: 600,
            padding: '6px 11px', borderRadius: t.radius.pill, cursor: 'pointer',
          }}>{tr('clear')}</button>
        )}
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12,
        background: t.color.surfaceAlt, borderRadius: t.radius.pill, padding: '0 12px', height: 40,
        border: `1px solid ${t.color.border}`,
      }}>
        {Ico.search(t.color.textFaint, 15)}
        <input value={q} onChange={(e) => setQ(e.target.value)} autoFocus placeholder={tr('searchIcons')}
          style={{ flex: '1 1 auto', minWidth: 0, border: 'none', outline: 'none', background: 'transparent', fontFamily: t.font.body, fontSize: 14.5, fontWeight: 500, color: t.color.text }} />
        {q && (
          <button onClick={() => setQ('')} aria-label="clear search" style={{ flex: '0 0 auto', border: 'none', background: 'transparent', cursor: 'pointer', padding: 4, display: 'flex' }}>
            {Ico.x(t.color.textFaint, 12)}
          </button>
        )}
      </div>
      <div className="noscroll" style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 4, maxHeight: 232, overflowY: 'auto' }}>
        {shown.map((e, i) => {
          const active = e === item.emoji;
          return (
            <button key={e + i} onClick={() => onPick(e)} style={{
              aspectRatio: '1 / 1', borderRadius: t.radius.chip, fontSize: 21, lineHeight: 1,
              border: active ? `2px solid ${t.color.accent}` : '1px solid transparent',
              background: active ? t.color.accentSoft : t.color.surfaceAlt, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'transform .1s, background .12s', padding: 0,
            }}
            onMouseDown={(ev) => (ev.currentTarget.style.transform = 'scale(.86)')}
            onMouseUp={(ev) => (ev.currentTarget.style.transform = 'scale(1)')}
            onMouseLeave={(ev) => (ev.currentTarget.style.transform = 'scale(1)')}>
              {e}
            </button>
          );
        })}
      </div>
      {shown.length === 0 && (
        <div style={{ padding: '26px 12px 18px', textAlign: 'center', color: t.color.textFaint, fontSize: 13.5 }}>{tr('noIcons')} “{q.trim()}”</div>
      )}
    </Sheet>
  );
}

// ── item detail sheet: rename + note + change icon + delete ─────────
function ItemSheet({ t, locale, item, list, onSave, onChangeIcon, onStep, onDelete, onClose }) {
  const L = window.I18N_T ? window.I18N_T(locale || 'en') : null;
  const tr = (k) => (L ? L.ui(k) : k);
  const trItem = (n) => (L ? L.item(n) : n);
  const [name, setName] = useS('');
  const [note, setNote] = useS('');
  useE(() => { setName(item ? trItem(item.name) : ''); setNote(item ? (item.note || '') : ''); }, [item && item.id]);
  if (!item) return null;
  const commit = () => { const typed = name.trim(); const init = trItem(item.name); const finalName = (typed && typed !== init) ? typed : item.name; onSave(item.id, finalName, note.trim()); };
  const fieldStyle = {
    width: '100%', boxSizing: 'border-box', border: `1px solid ${t.color.border}`, outline: 'none',
    background: t.color.surfaceAlt, borderRadius: Math.max(10, t.radius.chip), padding: '11px 13px',
    fontFamily: t.font.body, fontSize: 15, fontWeight: 500, color: t.color.text,
  };
  return (
    <Sheet t={t} onClose={() => { commit(); onClose(); }} z={50}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 14 }}>
        <button onClick={() => onChangeIcon(item.id)} title="Change icon" style={{
          flex: '0 0 auto', width: 46, height: 46, borderRadius: t.radius.chip, background: t.color.surfaceAlt,
          border: `1px solid ${t.color.border}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 25, lineHeight: 1, padding: 0,
        }}>
          {item.emoji || <span style={{ fontFamily: t.font.head, fontSize: 18, fontWeight: 700, color: t.color.textFaint }}>{(trItem(item.name).trim()[0] || '?').toUpperCase()}</span>}
        </button>
        <div style={{ flex: '1 1 auto', minWidth: 0 }}>
          <div style={{ fontFamily: t.font.head, fontSize: 16, fontWeight: 700, color: t.color.text }}>{tr('editItem')}</div>
          <button onClick={() => onChangeIcon(item.id)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, marginTop: 2, color: t.color.accent, fontFamily: t.font.head, fontSize: 12.5, fontWeight: 600 }}>{tr('changeIcon')}</button>
        </div>
        {list.showQty && (
          <div style={{ flex: '0 0 auto' }}>
            <window.Stepper t={t} item={item} onStep={(d) => onStep(item.id, d)} />
          </div>
        )}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        <input value={name} onChange={(e) => setName(e.target.value)} placeholder={tr('itemName')} style={fieldStyle}
          onKeyDown={(e) => { if (e.key === 'Enter') { commit(); onClose(); } }} />
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 9, ...fieldStyle, padding: '11px 13px' }}>
          <span style={{ flex: '0 0 auto', marginTop: 1 }}>{Ico.note(t.color.textFaint, 15)}</span>
          <input value={note} onChange={(e) => setNote(e.target.value)} placeholder={tr('addNote')}
            style={{ flex: '1 1 auto', minWidth: 0, border: 'none', outline: 'none', background: 'transparent', fontFamily: t.font.body, fontSize: 14, fontWeight: 500, color: t.color.text }}
            onKeyDown={(e) => { if (e.key === 'Enter') { commit(); onClose(); } }} />
        </div>
      </div>
      <div style={{ display: 'flex', gap: 9, marginTop: 14 }}>
        <button onClick={() => { onDelete(item.id); onClose(); }} style={{
          flex: '0 0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
          padding: '12px 16px', borderRadius: t.radius.pill, border: `1px solid ${t.color.border}`,
          background: 'transparent', color: t.color.danger, cursor: 'pointer', fontFamily: t.font.head, fontSize: 14, fontWeight: 600,
        }}>
          {Ico.trash(t.color.danger, 15)} {tr('delete')}
        </button>
        <button onClick={() => { commit(); onClose(); }} style={{
          flex: '1 1 auto', padding: '12px 16px', borderRadius: t.radius.pill, border: 'none',
          background: t.color.accent, color: t.color.accentText, cursor: 'pointer', fontFamily: t.font.head, fontSize: 14, fontWeight: 700,
        }}>{tr('done')}</button>
      </div>
    </Sheet>
  );
}

// ── create / rename list sheet ──────────────────────────────────────
function ListSheet({ t, locale, sheet, onSubmit, onDelete, onClose }) {
  const L = window.I18N_T ? window.I18N_T(locale || 'en') : null;
  const tr = (k) => (L ? L.ui(k) : k);
  const trList = (n) => (L ? L.list(n) : n);
  const trType = (n) => (L ? L.type(n) : n);
  // sheet: { mode:'new'|'edit', list? }
  const editing = sheet && sheet.mode === 'edit';
  const [name, setName] = useS('');
  const [emoji, setEmoji] = useS('\uD83D\uDED2');
  const [type, setType] = useS('shopping');
  useE(() => {
    if (!sheet) return;
    if (editing) { setName(trList(sheet.list.name)); setEmoji(sheet.list.emoji); }
    else { setName(''); setEmoji('\uD83D\uDED2'); setType('shopping'); }
  }, [sheet && sheet.mode, sheet && (sheet.list ? sheet.list.id : 'new')]);
  if (!sheet) return null;
  const types = window.LIST_TYPES || [];
  const emojis = window.LIST_EMOJIS || [];
  const submit = () => {
    const typed = name.trim();
    let finalName;
    if (editing) { const init = trList(sheet.list.name); finalName = (typed && typed !== init) ? typed : sheet.list.name; }
    else { finalName = typed; }
    onSubmit({ name: finalName, emoji, type }); onClose();
  };
  return (
    <Sheet t={t} onClose={onClose} z={55}>
      <div style={{ fontFamily: t.font.head, fontSize: 17, fontWeight: 700, color: t.color.text, marginBottom: 13 }}>
        {editing ? tr('renameList') : tr('newList')}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 13 }}>
        <div style={{ flex: '0 0 auto', width: 46, height: 46, borderRadius: t.radius.chip, background: t.color.surfaceAlt, border: `1px solid ${t.color.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24 }}>{emoji}</div>
        <input value={name} onChange={(e) => setName(e.target.value)} autoFocus placeholder={tr('listName')}
          onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
          style={{ flex: '1 1 auto', minWidth: 0, boxSizing: 'border-box', border: `1px solid ${t.color.border}`, outline: 'none', background: t.color.surfaceAlt, borderRadius: Math.max(10, t.radius.chip), padding: '12px 13px', fontFamily: t.font.body, fontSize: 15.5, fontWeight: 500, color: t.color.text }} />
      </div>
      {/* emoji choices */}
      <div className="noscroll" style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 4, marginBottom: editing ? 16 : 14 }}>
        {emojis.map((e) => {
          const active = e === emoji;
          return (
            <button key={e} onClick={() => setEmoji(e)} style={{
              aspectRatio: '1 / 1', borderRadius: t.radius.chip, fontSize: 20, cursor: 'pointer',
              border: active ? `2px solid ${t.color.accent}` : '1px solid transparent',
              background: active ? t.color.accentSoft : t.color.surfaceAlt, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
            }}>{e}</button>
          );
        })}
      </div>
      {/* type (new only) */}
      {!editing && (
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontFamily: t.font.head, fontSize: 11, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: t.color.textFaint, marginBottom: 8 }}>{tr('listType')}</div>
          <div style={{ display: 'flex', gap: 7 }}>
            {types.map((tp) => {
              const sel = tp.key === type;
              return (
                <button key={tp.key} onClick={() => { setType(tp.key); if (emoji === '\uD83D\uDED2' || emojis.indexOf(emoji) < 3) setEmoji(tp.emoji); }} style={{
                  flex: '1 1 0', padding: '11px 8px', borderRadius: Math.max(10, t.radius.chip), cursor: 'pointer',
                  border: `1.5px solid ${sel ? t.color.accent : t.color.border}`,
                  background: sel ? t.color.accentSoft : 'transparent', color: sel ? t.color.accent : t.color.textMuted,
                  fontFamily: t.font.head, fontSize: 13, fontWeight: 600, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                }}>
                  <span style={{ fontSize: 18 }}>{tp.emoji}</span>
                  <span>{trType(tp.label)}</span>
                </button>
              );
            })}
          </div>
        </div>
      )}
      <div style={{ display: 'flex', gap: 9 }}>
        {editing && onDelete && (
          <button onClick={() => { onDelete(sheet.list.id); onClose(); }} style={{
            flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 7, padding: '12px 15px', borderRadius: t.radius.pill,
            border: `1px solid ${t.color.border}`, background: 'transparent', color: t.color.danger, cursor: 'pointer', fontFamily: t.font.head, fontSize: 14, fontWeight: 600,
          }}>{Ico.trash(t.color.danger, 15)} {tr('delete')}</button>
        )}
        <button onClick={submit} style={{
          flex: '1 1 auto', padding: '12px 16px', borderRadius: t.radius.pill, border: 'none',
          background: t.color.accent, color: t.color.accentText, cursor: 'pointer', fontFamily: t.font.head, fontSize: 14, fontWeight: 700,
        }}>{editing ? tr('save') : tr('createList')}</button>
      </div>
    </Sheet>
  );
}

// ── share sheet (mock): invite link + member list ──────────────────
function ShareSheet({ t, locale, list, onClose }) {
  const L = window.I18N_T ? window.I18N_T(locale || 'en') : null;
  const tr = (k) => (L ? L.ui(k) : k);
  const trList = (n) => (L ? L.list(n) : n);
  const [copied, setCopied] = useS(false);
  useE(() => { setCopied(false); }, [list && list.id]);
  if (!list) return null;
  const members = list.members || [{ name: 'You', color: '#7b8bff', me: true }];
  const link = 'lista.app/j/' + String(list.id || 'x7k2p9').slice(-6);
  const copy = () => { try { if (navigator.clipboard) navigator.clipboard.writeText('https://' + link); } catch (e) {} setCopied(true); setTimeout(() => setCopied(false), 1600); };
  return (
    <Sheet t={t} onClose={onClose} z={58}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 15 }}>
        <div style={{ flex: '0 0 auto', width: 44, height: 44, borderRadius: t.radius.chip, background: t.color.surfaceAlt, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 23 }}>{list.emoji}</div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: t.font.head, fontSize: 16, fontWeight: 700, color: t.color.text }}>{tr('shareList')}</div>
          <div style={{ fontSize: 12.5, color: t.color.textFaint, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{trList(list.name)}</div>
        </div>
      </div>
      <div style={{ fontFamily: t.font.head, fontSize: 11, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: t.color.textFaint, marginBottom: 8 }}>{tr('invite')}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: t.color.surfaceAlt, border: `1px solid ${t.color.border}`, borderRadius: Math.max(10, t.radius.chip), padding: '9px 10px 9px 12px', marginBottom: 16 }}>
        <span style={{ flex: '0 0 auto', display: 'inline-flex' }}>{Ico.link(t.color.textMuted, 16)}</span>
        <span dir="ltr" style={{ flex: '1 1 auto', minWidth: 0, fontFamily: t.font.body, fontSize: 13.5, color: t.color.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{link}</span>
        <button onClick={copy} style={{ flex: '0 0 auto', border: 'none', background: copied ? t.color.surfaceAlt : t.color.accent, color: copied ? t.color.accent : t.color.accentText, fontFamily: t.font.head, fontSize: 12.5, fontWeight: 700, padding: '8px 13px', borderRadius: t.radius.pill, cursor: 'pointer', transition: 'background .15s' }}>{copied ? tr('copied') : tr('copyLink')}</button>
      </div>
      <div style={{ fontFamily: t.font.head, fontSize: 11, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: t.color.textFaint, marginBottom: 6 }}>{tr('members')} · {members.length}</div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {members.map((m, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '9px 2px', borderTop: i ? `1px solid ${t.color.divider}` : 'none' }}>
            <span style={{ flex: '0 0 auto', width: 34, height: 34, borderRadius: '50%', background: m.color, color: '#fff', fontFamily: t.font.head, fontWeight: 700, fontSize: 14, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{m.name[0]}</span>
            <span style={{ flex: '1 1 auto', fontSize: 15, fontWeight: 500, color: t.color.text }}>{m.name}</span>
          </div>
        ))}
      </div>
      <button onClick={onClose} style={{ width: '100%', boxSizing: 'border-box', marginTop: 16, padding: '12px', borderRadius: t.radius.pill, border: 'none', background: t.color.accent, color: t.color.accentText, fontFamily: t.font.head, fontSize: 14, fontWeight: 700, cursor: 'pointer' }}>{tr('done')}</button>
    </Sheet>
  );
}

Object.assign(window, { Sheet, EmojiSheet, ItemSheet, ListSheet, ShareSheet });
})();
// sheets build 2

