/* Order page — builder direction, no summary, focused on building the order */
const OrderPage = ({ scale = 1 }) => {
  const [items, setItems] = React.useState({ 1: 1, 2: 0, 3: 0, 4: 0, 5: 0 });
  const [time, setTime] = React.useState('18:00');
  const [emailReceipt, setEmailReceipt] = React.useState(false);

  const pizzas = [
    { id: 1, name: 'Margherita',       desc: 'Tomatensaus, mozzarella, basilicum, oregano',         price: 10.00, color: '#dc2626', emoji: '🍅' },
    { id: 2, name: 'Salami',           desc: 'Tomatensaus, kaas, salami',                           price: 11.50, color: '#b91c1c', emoji: '🌶️' },
    { id: 3, name: 'Quattro Stagioni', desc: 'Ham, artisjok, champignons, olijven, kappertjes',     price: 12.50, color: '#a16207', emoji: '🍄' },
    { id: 4, name: 'Rucola',           desc: 'Mozzarella, parmaham, Parmezaan, rucola',             price: 12.00, color: '#15803d', emoji: '🌿' },
    { id: 5, name: 'Napolitana',       desc: 'Olijven, ansjovis, kappertjes, Spaanse peper',        price: 12.00, color: '#1d4ed8', emoji: '🫒' },
  ];

  const total = pizzas.reduce((s, p) => s + p.price * (items[p.id] || 0), 0);
  const totalQty = Object.values(items).reduce((a, b) => a + b, 0);
  const inc = (id) => setItems({ ...items, [id]: Math.min(8, (items[id] || 0) + 1) });
  const dec = (id) => setItems({ ...items, [id]: Math.max(0, (items[id] || 0) - 1) });

  // Generate slots: every 5 min from 17:00 to 20:25 (42 slots). Mark some as full.
  const allSlots = [];
  for (let h = 17; h <= 20; h++) {
    for (let m = 0; m < 60; m += 5) {
      if (h === 20 && m > 25) break;
      allSlots.push(`${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}`);
    }
  }
  // Demo: a handful of slots are "full" (peak times)
  const fullSlots = new Set(['17:30','18:00','18:05','18:10','18:30','19:00','19:15','19:20']);

  // Group by hour for cleaner scanning
  const slotsByHour = {};
  allSlots.forEach(s => {
    const h = s.slice(0,2);
    (slotsByHour[h] = slotsByHour[h] || []).push(s);
  });

  return (
    <div style={{ background: '#fef3c7', minHeight: '100%', color: '#1c1917', fontFamily: '"Inter", system-ui, sans-serif' }}>
      <BuilderHeader subtitle="Bestel hieronder · betaal direct · ophalen op zaterdag" />
      <Steps active={1} />

      <div style={{ padding: '32px 24px 0' }}>
        <SectionTitle>Kies je pizza's</SectionTitle>
        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {pizzas.map(p => {
            const qty = items[p.id] || 0;
            const selected = qty > 0;
            return (
              <div key={p.id} style={{
                background: '#fff', borderRadius: 16, padding: 16, display: 'flex', gap: 14, alignItems: 'center',
                border: `2px solid ${selected ? p.color : 'transparent'}`,
                boxShadow: selected ? `0 6px 0 ${p.color}` : '0 3px 0 #fbbf24',
                position: 'relative',
              }}>
                {selected && (
                  <div style={{
                    position: 'absolute', top: -8, right: -8, background: p.color, color: '#fff',
                    width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 800, fontSize: 13, fontVariantNumeric: 'tabular-nums', boxShadow: '0 2px 6px rgba(0,0,0,0.15)',
                  }}>{qty}</div>
                )}
                <div style={{
                  width: 64, height: 64, borderRadius: 14, flexShrink: 0,
                  background: `linear-gradient(135deg, ${p.color}22, ${p.color}11)`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 32,
                  border: `2px dashed ${p.color}44`,
                }}>{p.emoji}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <h3 style={{ fontSize: 16, fontWeight: 800, margin: 0 }}>{p.name}</h3>
                  <p style={{ fontSize: 12.5, color: '#78716c', margin: '2px 0 6px', lineHeight: 1.4 }}>{p.desc}</p>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                    <span style={{ fontSize: 16, fontWeight: 800, color: p.color, fontVariantNumeric: 'tabular-nums' }}>
                      €{p.price.toFixed(2)}
                    </span>
                    <ChunkyStepper qty={qty} onInc={() => inc(p.id)} onDec={() => dec(p.id)} color={p.color} />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ padding: '28px 24px 0' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4 }}>
          <SectionTitle>Wanneer haal je op?</SectionTitle>
          <span style={{ fontSize: 11, color: '#78716c', fontWeight: 600 }}>Elke 5 min · ma haaltijd 20:25</span>
        </div>
        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {Object.entries(slotsByHour).map(([h, slots]) => (
            <div key={h}>
              <div style={{
                fontSize: 10, fontWeight: 800, color: '#a8a29e', letterSpacing: '0.18em',
                textTransform: 'uppercase', marginBottom: 6, fontVariantNumeric: 'tabular-nums',
              }}>{h}:00 — {h}:55</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6 }}>
                {slots.map(s => {
                  const full = fullSlots.has(s);
                  const selected = time === s;
                  return (
                    <button key={s} onClick={() => !full && setTime(s)} disabled={full} style={{
                      padding: '10px 0', borderRadius: 10, fontSize: 12, fontWeight: 800, fontVariantNumeric: 'tabular-nums',
                      border: 'none', cursor: full ? 'not-allowed' : 'pointer', fontFamily: 'inherit',
                      background: full ? '#f5f5f4' : (selected ? '#ea580c' : '#fff'),
                      color: full ? '#a8a29e' : (selected ? '#fff' : '#44403c'),
                      boxShadow: full ? 'none' : (selected ? '0 4px 0 #c2410c' : '0 2px 0 #fbbf24'),
                      textDecoration: full ? 'line-through' : 'none',
                      opacity: full ? 0.55 : 1,
                      position: 'relative',
                    }}>{s}</button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        {/* Legend */}
        <div style={{ marginTop: 12, display: 'flex', gap: 14, fontSize: 10.5, color: '#78716c', fontWeight: 600 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: '#ea580c' }} /> Gekozen
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: '#fff', boxShadow: '0 1px 0 #fbbf24', border: '1px solid #fde68a' }} /> Beschikbaar
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: '#f5f5f4', position: 'relative' }}>
              <span style={{ position: 'absolute', inset: 0, borderTop: '1px solid #a8a29e', transform: 'translateY(4px) rotate(-20deg)' }} />
            </span> Vol
          </span>
        </div>

        <div style={{
          marginTop: 12, background: '#fef9c3', border: '2px dashed #facc15', borderRadius: 12,
          padding: '10px 12px', fontSize: 11.5, color: '#854d0e', lineHeight: 1.45,
        }}>
          ⓘ Je ophaaltijd is pas definitief na het afrekenen. Als het gekozen tijdslot ondertussen vol raakt, kan je definitieve ophaaltijd iets later worden.
        </div>
      </div>

      <div style={{ padding: '28px 24px 0' }}>
        <SectionTitle>Jouw gegevens</SectionTitle>
        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <ChunkyInput placeholder="Naam *" />
          <ChunkyInput placeholder="Telefoonnummer *" type="tel" />
          <textarea placeholder="Opmerking (optioneel) — bijv. geen ui, extra goed doorbakken…" style={{
            width: '100%', padding: '14px 16px', border: '2px solid transparent',
            borderRadius: 12, background: '#fff', boxShadow: '0 3px 0 #fbbf24',
            fontFamily: 'inherit', fontSize: 14, resize: 'none', minHeight: 64, outline: 'none',
          }} />
          <label onClick={() => setEmailReceipt(!emailReceipt)} style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 12,
            background: emailReceipt ? '#fff7ed' : '#fff', boxShadow: '0 3px 0 #fbbf24',
            cursor: 'pointer', fontSize: 13, fontWeight: 600, color: '#44403c',
            border: `2px solid ${emailReceipt ? '#ea580c' : 'transparent'}`,
          }}>
            <span style={{
              width: 22, height: 22, borderRadius: 6, border: `2px solid ${emailReceipt ? '#ea580c' : '#d6d3d1'}`,
              background: emailReceipt ? '#ea580c' : '#fff',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 13,
            }}>{emailReceipt && '✓'}</span>
            Stuur me een bon per e-mail
          </label>
          {emailReceipt && (
            <ChunkyInput placeholder="E-mailadres *" type="email" />
          )}
        </div>
      </div>

      {/* Sticky bottom CTA — small total preview, no full summary */}
      <div style={{ padding: '32px 24px 32px', position: 'sticky', bottom: 0,
        background: 'linear-gradient(180deg, transparent 0%, #fef3c7 30%)',
      }}>
        <button disabled={totalQty === 0} style={{
          width: '100%', padding: '18px 22px', borderRadius: 16, border: 'none',
          background: totalQty === 0 ? '#d6d3d1' : '#ea580c', color: '#fff',
          fontSize: 16, fontWeight: 900, fontFamily: 'inherit',
          cursor: totalQty === 0 ? 'not-allowed' : 'pointer',
          boxShadow: totalQty === 0 ? 'none' : '0 6px 0 #c2410c',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10,
        }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ background: 'rgba(0,0,0,0.18)', padding: '4px 11px', borderRadius: 100, fontSize: 13, minWidth: 28, textAlign: 'center' }}>{totalQty}</span>
            Naar overzicht
          </span>
          <span style={{ fontVariantNumeric: 'tabular-nums' }}>€{total.toFixed(2)}</span>
        </button>
      </div>
    </div>
  );
};

const BuilderHeader = ({ subtitle }) => (
  <div style={{
    background: '#ea580c', color: '#fff', padding: '32px 24px 56px', position: 'relative',
    clipPath: 'polygon(0 0, 100% 0, 100% calc(100% - 24px), 50% 100%, 0 calc(100% - 24px))',
  }}>
    <div style={{ position: 'absolute', inset: 0, opacity: 0.12,
      backgroundImage: 'repeating-linear-gradient(45deg, #fff 0 2px, transparent 2px 12px)' }} />
    <div style={{ position: 'relative', textAlign: 'center' }}>
      <div style={{
        display: 'inline-block', background: '#fff', color: '#ea580c',
        padding: '4px 12px', borderRadius: 100, fontSize: 10, fontWeight: 800,
        letterSpacing: '0.15em', textTransform: 'uppercase',
      }}>Gouden Plakje · Pizza Friday</div>
      <h1 style={{ fontSize: 42, fontWeight: 900, margin: '12px 0 0', lineHeight: 0.95, letterSpacing: '-0.03em', textShadow: '0 4px 0 #c2410c' }}>
        Pizza Zaterdag
      </h1>
      <div style={{ fontSize: 12.5, marginTop: 6, opacity: 0.95 }}>{subtitle}</div>
    </div>
  </div>
);

const Steps = ({ active }) => (
  <div style={{ padding: '0 24px', marginTop: -28, position: 'relative' }}>
    <div style={{
      background: '#fff', borderRadius: 16, padding: '12px 16px', boxShadow: '0 8px 0 #fbbf24, 0 12px 24px rgba(0,0,0,0.08)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, fontWeight: 700,
    }}>
      <Step n="1" label="Bestellen" active={active >= 1} done={active > 1} />
      <Stepline />
      <Step n="2" label="Overzicht" active={active >= 2} done={active > 2} />
      <Stepline />
      <Step n="3" label="Betalen" active={active >= 3} done={active > 3} />
      <Stepline />
      <Step n="4" label="Klaar!" active={active >= 4} done={false} />
    </div>
  </div>
);

const Step = ({ n, label, active, done }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 6, opacity: active ? 1 : 0.4 }}>
    <span style={{
      width: 22, height: 22, borderRadius: '50%', background: active ? '#ea580c' : '#e7e5e4',
      color: active ? '#fff' : '#78716c', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 11, fontWeight: 800,
    }}>{done ? '✓' : n}</span>
    <span style={{ color: '#44403c' }}>{label}</span>
  </div>
);

const Stepline = () => <div style={{ flex: 1, height: 2, background: '#e7e5e4', margin: '0 4px' }} />;

const SectionTitle = ({ children }) => (
  <h2 style={{ fontSize: 22, fontWeight: 900, margin: 0, color: '#1c1917', letterSpacing: '-0.01em' }}>
    {children}
  </h2>
);

const ChunkyInput = ({ placeholder, type = 'text' }) => (
  <input type={type} placeholder={placeholder} style={{
    width: '100%', padding: '14px 16px', border: '2px solid transparent',
    borderRadius: 12, background: '#fff', boxShadow: '0 3px 0 #fbbf24',
    fontFamily: 'inherit', fontSize: 14, outline: 'none', color: '#1c1917',
  }} />
);

const ChunkyStepper = ({ qty, onInc, onDec, color }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
    <button onClick={onDec} disabled={qty === 0} style={{
      width: 32, height: 32, borderRadius: 10, border: 'none', cursor: qty === 0 ? 'not-allowed' : 'pointer',
      background: qty === 0 ? '#f5f5f4' : '#fed7aa', color: qty === 0 ? '#d6d3d1' : color,
      fontSize: 18, fontWeight: 800, fontFamily: 'inherit',
    }}>−</button>
    <div style={{ width: 32, textAlign: 'center', fontWeight: 800, fontSize: 16, fontVariantNumeric: 'tabular-nums', color: qty > 0 ? color : '#a8a29e' }}>
      {qty}
    </div>
    <button onClick={onInc} style={{
      width: 32, height: 32, borderRadius: 10, border: 'none', cursor: 'pointer',
      background: color, color: '#fff', fontSize: 18, fontWeight: 800, fontFamily: 'inherit',
    }}>+</button>
  </div>
);

window.OrderPage = OrderPage;
window.BuilderHeader = BuilderHeader;
window.Steps = Steps;
window.SectionTitle = SectionTitle;
