// app/screen-scan.jsx — /cook · point the camera at the fridge. AI detects
// items with confidence, you correct the list, then it suggests dinners.

const SCAN_BOXES = [
  { top: '15%', left: '18%', w: 72, h: 72, label: 'chicken' },
  { top: '42%', left: '52%', w: 60, h: 60, label: 'chilli oil' },
  { top: '60%', left: '14%', w: 56, h: 56, label: 'garlic' },
  { top: '24%', left: '70%', w: 60, h: 60, label: 'spring onion' },
];

function ScanScreen() {
  const { layout, SCAN_ITEMS, allRecipes, openRecipe, photoFor } = useApp();
  const isMobile = layout === 'mobile';
  const [items, setItems] = React.useState(() => SCAN_ITEMS.map((x, i) => ({ ...x, id: i, on: true })));
  const [adding, setAdding] = React.useState('');
  const [showResults, setShowResults] = React.useState(false);

  const remove = (id) => setItems((xs) => xs.filter((x) => x.id !== id));
  const toggle = (id) => setItems((xs) => xs.map((x) => (x.id === id ? { ...x, on: !x.on } : x)));
  const addItem = () => {
    if (!adding.trim()) return;
    setItems((xs) => [...xs, { id: Date.now(), item: adding.trim(), conf: 100, on: true }]);
    setAdding('');
  };

  // matching recipes — simple ingredient/word overlap
  const matches = React.useMemo(() => {
    const have = items.filter((x) => x.on).map((x) => x.item.toLowerCase());
    const scored = allRecipes.map((r) => {
      const hay = (r.name + ' ' + r.ingredients.join(' ')).toLowerCase();
      const score = have.reduce((s, h) => {
        const key = h.split(/[ ,(]/)[0];
        return s + (key.length > 2 && hay.includes(key) ? 1 : 0);
      }, 0);
      return { r, score };
    }).filter((x) => x.score > 0).sort((a, b) => b.score - a.score);
    return scored.slice(0, 8).map((x) => x.r);
  }, [items, allRecipes]);

  const Capture = (
    <div style={{ position: 'relative', aspectRatio: '4 / 3', borderRadius: 18, overflow: 'hidden',
      background: 'rgba(0,0,0,0.5)', border: '1px solid var(--hairline)' }}>
      <img src="assets/sichuan-chicken.png" alt="" style={{ width: '100%', height: '100%',
        objectFit: 'cover', opacity: 0.62 }} />
      <div style={{ position: 'absolute', inset: 0 }}>
        {SCAN_BOXES.map((b, i) => (
          <div key={i} style={{ position: 'absolute', top: b.top, left: b.left, width: b.w, height: b.h,
            border: '1.5px solid var(--olive)', background: 'rgba(240,168,80,0.10)', borderRadius: 4,
            boxShadow: '0 0 0 2px rgba(12,12,14,0.6)' }}>
            <span style={{ position: 'absolute', top: -22, left: 0, padding: '2px 6px', borderRadius: 4,
              background: 'var(--olive)', color: '#1a1208', fontFamily: 'Bricolage Grotesque',
              fontSize: 10, fontWeight: 600, whiteSpace: 'nowrap' }}>{b.label}</span>
          </div>
        ))}
      </div>
      <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16, display: 'flex',
        alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <FButton size={isMobile ? 'm' : 'l'} style={{ background: 'rgba(12,12,14,0.7)', color: 'var(--ink)',
          border: '1px solid rgba(255,255,255,0.18)', boxShadow: 'none', backdropFilter: 'blur(10px)' }}>
          <Icon.camera size={16} />{isMobile ? 'Photo' : 'Take another photo'}
        </FButton>
        <span style={{ flex: 1 }} />
        <FPill style={{ background: 'rgba(12,12,14,0.7)', backdropFilter: 'blur(10px)',
          border: '1px solid rgba(240,168,80,0.30)', color: 'var(--olive)' }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--olive)' }} />
          {items.length} items detected
        </FPill>
      </div>
    </div>
  );

  const List = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: 10, fontWeight: 600,
          letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--olive)' }}>
          What we found · {items.length} items
        </span>
        <span style={{ flex: 1, height: 1, background: 'var(--hairline-2)' }} />
        <span style={{ fontFamily: 'Spectral', fontStyle: 'italic', fontSize: 12, color: 'var(--ink-3)' }}>tap to keep · ✕ to remove</span>
      </div>
      <div style={{ background: 'rgba(255,255,255,0.025)', border: '1px solid var(--hairline)',
        borderRadius: 14, padding: 8, maxHeight: isMobile ? 'none' : 360, overflowY: 'auto' }}>
        {items.map((it) => (
          <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
            borderRadius: 8, marginBottom: 4,
            background: it.wrong ? 'rgba(217,106,74,0.06)' : 'transparent',
            border: it.wrong ? '1px solid rgba(217,106,74,0.20)' : '1px solid transparent' }}>
            <button onClick={() => toggle(it.id)} style={{ width: 18, height: 18, borderRadius: 4, flexShrink: 0,
              border: it.on ? 'none' : '1.5px solid var(--ink-3)', cursor: 'pointer',
              background: it.on ? 'linear-gradient(135deg, #f0a850, #c97818)' : 'transparent',
              color: '#1a1208', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
              {it.on && <Icon.check size={11} stroke={3} />}
            </button>
            <span style={{ fontFamily: 'Spectral', fontSize: 15, flex: 1,
              color: it.on ? 'var(--ink)' : 'var(--ink-4)', textDecoration: it.on ? 'none' : 'line-through' }}>{it.item}</span>
            <div style={{ width: 32, height: 4, borderRadius: 999, background: 'rgba(255,255,255,0.06)',
              flexShrink: 0, overflow: 'hidden' }} title={`${it.conf}% confident`}>
              <div style={{ width: `${it.conf}%`, height: '100%',
                background: it.conf > 80 ? 'var(--olive)' : it.conf > 65 ? '#d9a04b' : '#d96a4a' }} />
            </div>
            <button onClick={() => remove(it.id)} style={{ background: 'transparent', border: 'none',
              cursor: 'pointer', color: 'var(--ink-3)', display: 'flex' }}><Icon.x size={14} /></button>
          </div>
        ))}
        <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
          <input value={adding} onChange={(e) => setAdding(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') addItem(); }}
            placeholder="+ add an item" style={{ flex: 1, padding: '10px 12px', borderRadius: 8,
              background: 'transparent', border: '1px dashed var(--hairline)', color: 'var(--ink)',
              fontFamily: 'Bricolage Grotesque', fontSize: 13, outline: 'none' }} />
          <FButton size="s" variant="ghost" onClick={addItem}>Add</FButton>
        </div>
      </div>
      <FButton size="xl" onClick={() => setShowResults(true)} style={{ minHeight: 58 }}>
        <Icon.sparkle size={18} />Show me what I can cook <span style={{ fontSize: 18 }}>→</span>
      </FButton>
    </div>
  );

  const Results = showResults && (
    <div style={{ padding: isMobile ? '0 18px 28px' : '0 48px 64px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: 11, fontWeight: 600,
          letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--olive)' }}>
          {matches.length} recipes you can make right now
        </span>
        <span style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)',
        gap: isMobile ? '24px 14px' : '32px 24px' }}>
        {matches.map((r) => (
          <div key={r.id} onClick={() => openRecipe(r.id)} style={{ cursor: 'pointer' }}>
            <FRecipeCard recipe={r} photoSrc={photoFor(r.id)} size={isMobile ? 's' : 'm'} />
          </div>
        ))}
      </div>
    </div>
  );

  const Intro = (
    <div style={{ padding: isMobile ? '24px 18px 8px' : '40px 48px 24px' }}>
      <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: isMobile ? 10 : 11, fontWeight: 600,
        letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--olive)' }}>What can I cook?</span>
      <h1 style={{ fontFamily: 'Bricolage Grotesque', fontWeight: 700, fontSize: isMobile ? 38 : 80,
        lineHeight: 0.92, letterSpacing: '-0.045em', color: 'var(--ink)', margin: '10px 0 0' }}>
        Show us
        <span style={{ fontFamily: 'Spectral', fontStyle: 'italic', fontWeight: 400, color: 'var(--olive)' }}> the fridge.</span>
      </h1>
      <p style={{ fontFamily: 'Spectral', fontStyle: 'italic', fontSize: isMobile ? 16 : 20, lineHeight: 1.55,
        color: 'var(--ink-2)', margin: '14px 0 0', maxWidth: 720 }}>
        We'll list what we see — correct it before we suggest dinners. AI gets things wrong; you have the final say.
      </p>
    </div>
  );

  return (
    <Shell tab="cook">
      {Intro}
      <div style={{ padding: isMobile ? '20px 18px 24px' : '24px 48px 40px', display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.15fr 1fr', gap: isMobile ? 24 : 36 }}>
        {Capture}
        {List}
      </div>
      {Results}
    </Shell>
  );
}

Object.assign(window, { ScanScreen });
