// Main canvas screens — welcome, fridge, recipes, recipe-detail, basket, checkout, tracking, pantry.

const { useState: useS, useEffect: useE, useMemo, useRef: useR } = React;

/* --- shared --- */
const PThumb = ({ p, className, style }) =>
  p && p.img
    ? <img src={p.img} alt={p.name} className={className} style={{ width: '78%', height: '78%', objectFit: 'contain', ...style }}/>
    : <Glyph kind={p.glyph} className={className} style={style}/>;

const ProductCard = ({ p, inBasket, onAdd }) => (
  <div className={`product ${inBasket ? 'in-basket' : ''}`}>
    <div className="product-thumb">
      <PThumb p={p} className="glyph"/>
      <span className="sku">{p.sku}</span>
      {inBasket && <span className="badge accent">in basket</span>}
    </div>
    <div className="product-name">{p.name}</div>
    <div className="product-sub">{p.sub}</div>
    <div className="product-foot">
      <span className="product-price">${p.price.toFixed(2)}</span>
      <button className="product-add" onClick={() => onAdd(p.id)} aria-label="Add">
        {inBasket ? <Icon.check/> : <Icon.plus/>}
      </button>
    </div>
  </div>
);

const CanvasHeader = ({ crumb, title, subtitle, right }) => (
  <header className="canvas-header">
    <div>
      <div className="crumb"><span className="dot"/><span>{crumb}</span></div>
      <h1 dangerouslySetInnerHTML={{ __html: title }}/>
      {subtitle && <p className="muted" style={{ marginTop: 14, maxWidth: 560, fontSize: 15, lineHeight: 1.5 }}>{subtitle}</p>}
    </div>
    {right}
  </header>
);

/* ============================================
   WELCOME
   ============================================ */
const Welcome = ({ onAction, onSend, listening }) => {
  const time = new Date().getHours();
  const greet = time < 12 ? 'morning' : time < 18 ? 'afternoon' : 'evening';

  return (
    <div className="welcome">
      <div style={{ position: 'relative' }}>
        <Orb size={220} listening={listening}/>
        {listening && (
          <div style={{ position: 'absolute', top: '100%', left: '50%', transform: 'translate(-50%, 32px)', whiteSpace: 'nowrap' }}>
            <div className="voice-bar">
              <div className="wave"><span/><span/><span/><span/><span/><span/><span/></div>
              <span className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>listening…</span>
            </div>
          </div>
        )}
      </div>

      <div>
        <h1>
          Good {greet}, Maya.<br/>
          <em>what's for dinner?</em>
        </h1>
        <p>Talk, type or drop a fridge photo. I'll find a recipe, fill the basket, and skip what you already own.</p>
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center', maxWidth: 720 }}>
        {BLYZR.welcomePrompts.map((p) => {
          const I = Icon[p.icon] || Icon.spark;
          return (
            <button key={p.id} className="chip" onClick={() => onSend(p.label)} style={{ padding: '10px 14px', fontSize: 13 }}>
              <I style={{ width: 14, height: 14 }}/>
              {p.label}
            </button>
          );
        })}
      </div>
    </div>
  );
};

/* ============================================
   FRIDGE SCAN
   ============================================ */
const FridgeScan = ({ scanned, onSend, onAdd, basket }) => {
  const [scanning, setScanning] = useS(false);

  useE(() => {
    if (scanned) setScanning(true);
  }, [scanned]);

  return (
    <>
      <CanvasHeader
        crumb="01 — scan"
        title="Show me <em>what's in there.</em>"
        subtitle="Drop a photo of your fridge. I'll catalogue what you've got, flag what's running out, and build a shopping list around it."
      />

      <div className="grid-2" style={{ gridTemplateColumns: '1fr 1fr', gap: 24, alignItems: 'start' }}>
        {/* Fridge stage */}
        <div className="fridge-stage">
          {/* Mock fridge contents — abstract shelf layout */}
          <svg viewBox="0 0 400 480" style={{ width: '100%', height: '100%', position: 'absolute', inset: 0 }}>
            <defs>
              <pattern id="grain" patternUnits="userSpaceOnUse" width="4" height="4">
                <rect width="4" height="4" fill="oklch(0.96 0.005 95)"/>
              </pattern>
            </defs>
            <rect width="400" height="480" fill="url(#grain)"/>
            {/* shelves */}
            <line x1="0" y1="160" x2="400" y2="160" stroke="oklch(0.85 0.008 90)" strokeWidth="1"/>
            <line x1="0" y1="320" x2="400" y2="320" stroke="oklch(0.85 0.008 90)" strokeWidth="1"/>
            {/* abstract items */}
            <g opacity="0.9">
              {/* tomatoes top-left */}
              <circle cx="56" cy="100" r="14" fill="oklch(0.65 0.18 30)" opacity="0.5"/>
              <circle cx="82" cy="106" r="13" fill="oklch(0.65 0.18 30)" opacity="0.5"/>
              <circle cx="108" cy="100" r="13" fill="oklch(0.65 0.18 30)" opacity="0.5"/>
              <circle cx="86" cy="86" r="12" fill="oklch(0.65 0.18 30)" opacity="0.5"/>
              {/* eggs top-right */}
              <ellipse cx="270" cy="100" rx="12" ry="16" fill="oklch(0.88 0.04 80)"/>
              <ellipse cx="300" cy="105" rx="12" ry="16" fill="oklch(0.88 0.04 80)"/>
              {/* milk left */}
              <rect x="34" y="260" width="60" height="80" rx="4" fill="oklch(0.96 0.005 95)" stroke="oklch(0.82 0.008 90)" strokeWidth="1"/>
              <rect x="40" y="270" width="48" height="10" fill="oklch(0.78 0.16 240)" opacity="0.3"/>
              {/* spinach middle */}
              <rect x="160" y="240" width="92" height="50" rx="6" fill="oklch(0.85 0.10 135)" opacity="0.3"/>
              {/* butter right */}
              <rect x="290" y="300" width="70" height="40" rx="4" fill="oklch(0.94 0.06 90)"/>
            </g>
          </svg>

          {scanning && (
            <>
              <div className="fridge-scan-line"/>
              {BLYZR.fridgeDetections.map((d, i) => (
                <div
                  key={d.id}
                  className="fridge-detection"
                  style={{
                    left: `${d.x}%`,
                    top: `${d.y}%`,
                    width: `${d.w}%`,
                    height: `${d.h}%`,
                    animation: `fade-up 0.5s ${0.4 + i * 0.18}s cubic-bezier(0.2, 0.7, 0.2, 1) both`,
                  }}
                >
                  <span className="tag">{d.label}</span>
                </div>
              ))}
            </>
          )}

          {!scanning && (
            <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', background: 'oklch(0.99 0.003 100 / 0.55)', backdropFilter: 'blur(8px)' }}>
              <div style={{ textAlign: 'center', padding: 40 }}>
                <div style={{ width: 56, height: 56, margin: '0 auto 16px', borderRadius: '50%', background: 'var(--bg)', border: '1px solid var(--border)', display: 'grid', placeItems: 'center', boxShadow: 'var(--shadow-md)', color: 'var(--ink-2)' }}>
                  <Icon.camera/>
                </div>
                <div style={{ fontFamily: 'var(--f-display)', fontStyle: 'italic', fontSize: 22, marginBottom: 6 }}>Drop a photo here</div>
                <div className="mono muted" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase' }}>or use device camera</div>
                <button className="btn btn-dark" style={{ marginTop: 18 }} onClick={() => setScanning(true)}>
                  Use demo fridge <Icon.arrow style={{ width: 14, height: 14 }}/>
                </button>
              </div>
            </div>
          )}

          {scanning && (
            <div style={{ position: 'absolute', bottom: 12, left: 12, right: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-3)', background: 'oklch(0.99 0.003 100 / 0.85)', padding: '4px 8px', borderRadius: 6, border: '1px solid var(--border)' }}>
                ⌬ vision · 5 items · confidence 0.94
              </span>
            </div>
          )}
        </div>

        {/* Detections panel */}
        <div>
          <div className="sec-head">
            <h3>{scanning ? 'Detected items' : 'Awaiting scan'}</h3>
            <span className="meta">{scanning ? `${BLYZR.fridgeDetections.length} found` : '—'}</span>
          </div>

          <div className="col gap-2">
            {scanning && BLYZR.fridgeDetections.map((d, i) => {
              const p = BLYZR.productById[d.id];
              const tone = d.action === 'out' ? 'var(--danger)' : d.action === 'low' ? 'var(--warm)' : d.action === 'restock' ? 'var(--warm)' : 'var(--accent)';
              const label = d.action === 'have' ? 'have it' : d.action === 'low' ? 'running low' : d.action === 'out' ? 'nearly out' : 'restock';
              return (
                <div key={d.id} className="list-card" style={{ animation: `fade-up 0.5s ${0.6 + i * 0.1}s both` }}>
                  <div style={{ width: 40, height: 40, borderRadius: 8, background: 'var(--surface-2)', display: 'grid', placeItems: 'center', color: 'var(--ink-3)' }}>
                    <Glyph kind={p.glyph} style={{ width: 24, height: 24 }}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14 }}>{p.name}</div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', letterSpacing: '0.06em', marginTop: 2 }}>{d.label}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: tone, padding: '4px 8px', borderRadius: 999, border: `1px solid currentColor`, opacity: 0.9 }}>{label}</span>
                </div>
              );
            })}
          </div>

          {scanning && (
            <div className="glass" style={{ marginTop: 18, padding: 20, borderRadius: 18 }}>
              <div className="eyebrow" style={{ marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                <OrbMini/> Blyzr suggests
              </div>
              <div style={{ fontFamily: 'var(--f-display)', fontStyle: 'italic', fontSize: 22, lineHeight: 1.15, marginBottom: 14 }}>
                Spaghetti al pomodoro — uses 4 of these, ready in 22 min.
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button className="btn btn-accent" onClick={() => onSend('show me a 30 min italian with tomatoes')}>
                  Build the basket <Icon.arrow style={{ width: 14, height: 14 }}/>
                </button>
                <button className="btn btn-outline" onClick={() => onSend('what else can i make')}>Other ideas</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

window.Welcome = Welcome;
window.FridgeScan = FridgeScan;
window.ProductCard = ProductCard;
window.PThumb = PThumb;
window.CanvasHeader = CanvasHeader;
