// b/inventory.jsx — inventory reveal + saved + shopping-list sheets.

// Generic bottom sheet over a dimmed backdrop.
function Sheet({ children, onClose, motion, height = '82%', dim = true }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 50 }}>
      {dim && <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(18,18,16,.5)', animation: motion ? 'fade .25s ease' : 'none' }} />}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, maxHeight: height, height,
        background: T.paper, borderRadius: '22px 22px 0 0',
        boxShadow: '0 -16px 40px rgba(0,0,0,.3)', display: 'flex', flexDirection: 'column',
        animation: motion ? 'sheetUp .34s cubic-bezier(.2,.8,.25,1)' : 'none',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 10 }}>
          <span style={{ width: 40, height: 4, borderRadius: 2, background: T.faint }} />
        </div>
        {children}
      </div>
    </div>
  );
}

// Editable inventory: an AI guess the user corrects (or fills in from scratch),
// then matches against real sets.
const selStyle = {
  fontFamily: disp, fontSize: 13.5, color: T.ink, background: T.paper,
  border: '1px solid ' + T.line, borderRadius: 9, padding: '8px 6px', cursor: 'pointer',
};

function InvRow({ item, cat, onChange, onRemove }) {
  const color = cat.colors.find(c => c.key === item.color) || cat.colors[0];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '9px 0', borderBottom: '1px solid ' + T.line }}>
      <Swatch hex={color ? color.hex : '#9a988f'} size={24} />
      <select value={item.part} onChange={e => onChange({ part: e.target.value })} style={{ ...selStyle, flex: 1, minWidth: 0 }}>
        {cat.parts.map(p => <option key={p.key} value={p.key}>{p.da}</option>)}
      </select>
      <select value={item.color} onChange={e => onChange({ color: e.target.value })} style={{ ...selStyle, width: 84 }}>
        {cat.colors.map(c => <option key={c.key} value={c.key}>{c.da}</option>)}
      </select>
      <div style={{ display: 'flex', alignItems: 'center', border: '1px solid ' + T.line, borderRadius: 9 }}>
        <button onClick={() => onChange({ count: Math.max(1, (Number(item.count) || 1) - 1) })} style={stepBtn}>–</button>
        <span style={{ width: 26, textAlign: 'center', fontFamily: mono, fontSize: 12, color: T.ink }}>{item.count}</span>
        <button onClick={() => onChange({ count: (Number(item.count) || 1) + 1 })} style={stepBtn}>+</button>
      </div>
      <button onClick={onRemove} style={{ background: 'none', border: 'none', cursor: 'pointer', color: T.ink2, fontSize: 15, padding: '0 2px' }}>✕</button>
    </div>
  );
}
const stepBtn = { background: 'none', border: 'none', cursor: 'pointer', color: T.ink, fontSize: 16, width: 24, height: 28, lineHeight: '24px' };

function InventoryReveal({ items, onItems, source, onClose, onFind, finding, motion, catalog }) {
  const cat = catalog || window.CATALOG || { parts: [], colors: [] };
  const total = items.reduce((a, it) => a + (Number(it.count) || 0), 0);
  const srcLabel = source === 'api' ? 'AI-GÆT · RET VENLIGST' : 'INDTAST DIT INVENTAR';

  const update = (i, patch) => onItems(items.map((it, k) => k === i ? { ...it, ...patch } : it));
  const remove = (i) => onItems(items.filter((_, k) => k !== i));
  const add = () => onItems([...items, { part: (cat.parts[0] || {}).key || 'brick-2x4', color: (cat.colors[0] || {}).key || 'red', count: 4 }]);

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.screen }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(120% 80% at 50% 25%, #23211c 0%, #0e0d0a 100%)', opacity: .5 }} />
      <div style={{ position: 'absolute', top: 30, left: 0, right: 0, textAlign: 'center', color: '#f7f5ee' }}>
        <div style={{ fontFamily: mono, fontSize: 10.5, opacity: .8, letterSpacing: 1 }}>{source === 'api' ? '✓ ' : ''}{srcLabel}</div>
      </div>

      <Sheet motion={motion} dim={false} height="88%">
        <div style={{ padding: '6px 20px 0', overflow: 'hidden', display: 'flex', flexDirection: 'column', height: '100%' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', paddingTop: 6 }}>
            <div>
              <div style={{ fontFamily: mono, fontSize: 10.5, color: T.ink2, letterSpacing: 0.5 }}>DIT INVENTAR</div>
              <div style={{ fontFamily: disp, fontSize: 26, fontWeight: 700, color: T.ink, lineHeight: 1 }}>{total} klodser</div>
            </div>
            <div style={{ textAlign: 'right', fontFamily: mono, fontSize: 11, color: T.ink2 }}>{items.length} rækker</div>
          </div>

          <div style={{ fontFamily: disp, fontSize: 12, color: T.ink2, lineHeight: 1.45, marginTop: 8 }}>
            {source === 'api'
              ? 'AI’en gættede ud fra fotoet. Ret klods-typer, farver og antal, så matchet bliver præcist.'
              : 'Tilføj de klodser du har — vælg type, farve og antal. Jo mere præcist, jo bedre match.'}
          </div>

          <div style={{ flex: 1, overflowY: 'auto', marginTop: 12, paddingBottom: 10 }}>
            {items.map((it, i) => (
              <InvRow key={i} item={it} cat={cat} onChange={(p) => update(i, p)} onRemove={() => remove(i)} />
            ))}
            <button onClick={add} style={{ width: '100%', marginTop: 12, background: 'none', cursor: 'pointer',
              border: '1.5px dashed ' + T.line, borderRadius: 12, padding: '12px', fontFamily: mono, fontSize: 12, color: T.ink2 }}>
              + tilføj klods
            </button>
          </div>

          <div style={{ padding: '12px 0 calc(16px + env(safe-area-inset-bottom))', borderTop: '1px solid ' + T.line }}>
            <Btn onClick={onFind} disabled={finding || total === 0}>
              {finding ? 'Finder sæt…' : total === 0 ? 'Tilføj klodser først' : 'Find sæt du kan bygge →'}
            </Btn>
            <button onClick={onClose} style={{ width: '100%', background: 'none', border: 'none', cursor: 'pointer', marginTop: 10, fontFamily: mono, fontSize: 11, color: T.ink2 }}>
              scan igen
            </button>
          </div>
        </div>
      </Sheet>
    </div>
  );
}

function SavedSheet({ projects, savedIds, onClose, onOpen, motion }) {
  const saved = projects.filter(p => savedIds.includes(p.id));
  return (
    <Sheet motion={motion} onClose={onClose} height="76%">
      <div style={{ padding: '10px 20px 0', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontFamily: disp, fontSize: 22, fontWeight: 700, color: T.ink }}>Gemte projekter</div>
          <button onClick={onClose} style={{ ...iconBtn, width: 32, height: 32 }}>✕</button>
        </div>
        <div style={{ fontFamily: mono, fontSize: 11, color: T.ink2, marginTop: 2 }}>{saved.length} gemt</div>

        <div style={{ flex: 1, overflowY: 'auto', marginTop: 14, paddingBottom: 16 }}>
          {saved.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '50px 20px', fontFamily: disp, fontSize: 14, color: T.ink2, lineHeight: 1.5 }}>
              Ingen gemte endnu.<br/>Swipe et forslag opad — eller tryk ♥ — for at gemme det her.
            </div>
          ) : saved.map(p => (
            <button key={p.id} onClick={() => onOpen(p)} style={{ width: '100%', textAlign: 'left', background: 'none', cursor: 'pointer',
              border: '1px solid ' + T.line, borderRadius: 14, padding: 10, marginBottom: 10, display: 'flex', gap: 12, alignItems: 'center' }}>
              <div style={{ width: 64, height: 64, borderRadius: 10, background: `${p.palette[0]}1a`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <SetArt project={p} size={62} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: disp, fontSize: 16, fontWeight: 700, color: T.ink }}>{p.name}</div>
                <div style={{ display: 'flex', gap: 6, marginTop: 5, alignItems: 'center' }}>
                  <Chip>{p.year || '—'}</Chip>
                  <Chip accent={p.match >= 70}>{p.match}%</Chip>
                </div>
              </div>
              <span style={{ fontFamily: mono, fontSize: 16, color: T.ink2 }}>›</span>
            </button>
          ))}
        </div>
      </div>
    </Sheet>
  );
}

function ShoppingSheet({ items, onClose, onRemove, motion }) {
  const total = items.reduce((a, it) => a + it.price * it.q, 0);
  const count = items.reduce((a, it) => a + it.q, 0);
  return (
    <Sheet motion={motion} onClose={onClose} height="74%">
      <div style={{ padding: '10px 20px 0', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontFamily: disp, fontSize: 22, fontWeight: 700, color: T.ink }}>Indkøbsliste</div>
          <button onClick={onClose} style={{ ...iconBtn, width: 32, height: 32 }}>✕</button>
        </div>
        <div style={{ fontFamily: mono, fontSize: 11, color: T.ink2, marginTop: 2 }}>{count} klodser du mangler</div>

        <div style={{ flex: 1, overflowY: 'auto', marginTop: 14 }}>
          {items.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '50px 20px', fontFamily: disp, fontSize: 14, color: T.ink2, lineHeight: 1.5 }}>
              Listen er tom.<br/>Føj manglende klodser til fra et projekt for at samle dem her.
            </div>
          ) : items.map((it, i) => (
            <div key={it.name + i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: '1px solid ' + T.line }}>
              <span style={{ width: 30, height: 18, borderRadius: 3, background: T.faint, border: '1px solid rgba(0,0,0,.15)', flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: disp, fontSize: 14.5, color: T.ink }}>{it.name}</div>
                <div style={{ fontFamily: mono, fontSize: 10.5, color: T.ink2, marginTop: 2 }}>til {it.from}</div>
              </div>
              <span style={{ fontFamily: mono, fontSize: 11, color: T.ink2 }}>×{it.q}</span>
              <span style={{ fontFamily: mono, fontSize: 12, color: T.ink, width: 46, textAlign: 'right' }}>{it.price * it.q} kr</span>
              <button onClick={() => onRemove(i)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: T.ink2, fontSize: 15 }}>✕</button>
            </div>
          ))}
        </div>

        {items.length > 0 && (
          <div style={{ padding: '12px 0 calc(16px + env(safe-area-inset-bottom))', borderTop: '1.5px solid ' + T.ink }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
              <span style={{ fontFamily: mono, fontSize: 11, color: T.ink2 }}>ESTIMERET I ALT</span>
              <span style={{ fontFamily: disp, fontSize: 24, fontWeight: 700, color: T.ink }}>{total} kr</span>
            </div>
            <Btn>Find delene online →</Btn>
          </div>
        )}
      </div>
    </Sheet>
  );
}

Object.assign(window, { Sheet, InventoryReveal, SavedSheet, ShoppingSheet });
