// Burger House — Product detail page (the marquee page)

const ORDER_URL = 'https://www.ubereats.com/';

// Map an ingredient name to a generated photo in /public/ingredients/.
const ingredientImageSlug = (name) => {
  const n = (name || '').toLowerCase();
  if (n.includes('brioche') && n.includes('top'))    return 'brioche-bun-top';
  if (n.includes('brioche') && n.includes('bottom')) return 'brioche-bun-bottom';
  if (n.includes('sourdough') && n.includes('top'))    return 'sourdough-bun-top';
  if (n.includes('sourdough') && n.includes('bottom')) return 'sourdough-bun-bottom';
  if (n.includes('potato') && n.includes('top'))    return 'potato-bun-top';
  if (n.includes('potato') && n.includes('bottom')) return 'potato-bun-bottom';
  if (n.includes('cheddar'))           return 'aged-cheddar';
  if (n.includes('stilton'))           return 'stilton';
  if (n.includes('bean'))              return 'black-bean-beet-patty';
  if (n.includes('chicken thigh'))     return 'buttermilk-chicken-thigh';
  if (n.includes('patty'))             return 'beef-patty';
  if (n.includes('pickle'))            return 'pickles';
  if (n.includes('iceberg') || n.includes('lettuce')) return 'iceberg-lettuce';
  if (n.includes('rocket'))            return 'rocket';
  if (n.includes('slaw'))              return 'slaw';
  if (n.includes('tomato') && n.includes('relish')) return 'smoked-tomato-relish';
  if (n.includes('tomato'))            return 'tomato';
  if (n.includes('vegan aioli'))       return 'vegan-aioli';
  if (n.includes('hot honey'))         return 'hot-honey-glaze';
  if (n.includes('bbq'))               return 'bbq-glaze';
  if (n.includes('house sauce') || n.includes('aioli')) return 'house-sauce';
  if (n.includes('onion'))             return 'caramelised-onion';
  if (n.includes('bacon'))             return 'smoked-bacon';
  if (n.includes('avocado'))           return 'avocado';
  return null;
};

const IngredientIcon = ({ name, color, size = 44 }) => {
  const slug = ingredientImageSlug(name);
  if (slug) {
    return (
      <img
        src={`public/ingredients/${slug}.jpg`}
        alt={name}
        width={size} height={size}
        style={{ width: size, height: size, objectFit: 'cover', borderRadius: 10, display: 'block' }}
      />
    );
  }
  const s = size, c = size / 2;
  return (<svg width={s} height={s} viewBox="0 0 44 44"><circle cx={c} cy={c} r="14" fill={color}/></svg>);
};

const NutritionBar = ({ label, value, unit, pct, ri }) => (
  <div className="col gap-8" style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
    <div className="row between">
      <span style={{ fontSize: 14, fontWeight: 500 }}>{label}</span>
      <span className="mono" style={{ fontSize: 13 }}>{value}{unit}</span>
    </div>
    <div style={{ height: 4, background: 'var(--surface-2)', borderRadius: 2, overflow: 'hidden' }}>
      <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: pct > 70 ? 'var(--accent)' : 'var(--ink-2)' }} />
    </div>
    <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{pct}% of {ri}</span>
  </div>
);

const IngredientRow = ({ ing, totalCal, expanded, onToggle }) => {
  const pct = Math.round((ing.cal / totalCal) * 100);
  return (
    <div style={{ borderBottom: '1px solid var(--line)' }}>
      <button onClick={onToggle} style={{
        all: 'unset', cursor: 'pointer', width: '100%',
        display: 'flex', alignItems: 'center', gap: 16,
        padding: '16px 0',
      }}>
        <span className="swatch" style={{ background: ing.color }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.85)" strokeWidth="2.5">
            <path d="M5 12l5 5L20 7"/>
          </svg>
        </span>
        <div style={{ flex: 1 }}>
          <div className="row between">
            <span style={{ fontSize: 15, fontWeight: 500 }}>{ing.name}</span>
            <span className="mono" style={{ fontSize: 13, color: 'var(--ink-2)' }}>{ing.cal} kcal</span>
          </div>
          <div style={{ height: 3, background: 'var(--surface-2)', borderRadius: 2, marginTop: 8, overflow: 'hidden' }}>
            <div style={{ width: `${pct}%`, height: '100%', background: ing.color, transition: 'width .3s' }} />
          </div>
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3)" strokeWidth="2"
             style={{ transform: expanded ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}>
          <path d="M6 9l6 6 6-6"/>
        </svg>
      </button>
      {expanded && (
        <div style={{ paddingLeft: 44, paddingBottom: 16, paddingRight: 30 }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 8, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            {pct}% of total · {ing.cal} kcal
          </div>
          {ing.notes && <p style={{ fontSize: 13, color: 'var(--ink-2)', margin: 0 }}>{ing.notes}</p>}
        </div>
      )}
    </div>
  );
};

const ProductPage = ({ p, onNav }) => {
  const totalCal = p.calories;
  const RI = { fat: 70, satFat: 20, carbs: 260, sugars: 90, salt: 6, protein: 50 };

  return (
    <>
      <section style={{ padding: '24px 0 0' }}>
        <div className="container">
          <div className="row gap-8" style={{ fontSize: 13, color: 'var(--ink-3)', flexWrap: 'wrap' }}>
            <a onClick={() => onNav('home')} style={{ cursor: 'pointer' }}>Home</a>
            <span>/</span>
            <a onClick={() => onNav('menu')} style={{ cursor: 'pointer' }}>Menu</a>
            <span>/</span>
            <a onClick={() => onNav('category')} style={{ cursor: 'pointer' }}>{p.category}</a>
            <span>/</span>
            <span style={{ color: 'var(--ink)' }}>{p.name}</span>
          </div>
        </div>
      </section>

      <section style={{ padding: '24px 0 48px' }}>
        <div className="container product-grid" style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 56 }}>
          {/* Left — imagery */}
          <div>
            <div className="product-image" style={{
              background: 'var(--surface)',
              border: '1px solid var(--line)',
              borderRadius: 28,
              aspectRatio: '1', display: 'flex', alignItems: 'center', justifyContent: 'center',
              position: 'relative',
              overflow: 'hidden',
            }}>
              <div style={{
                position: 'absolute', inset: 0,
                background: 'radial-gradient(circle at 50% 60%, var(--accent-soft) 0%, transparent 60%)',
              }} />
              <img
                src={`public/${p.id}.jpg`}
                alt={p.name}
                style={{ width: '100%', height: '100%', objectFit: 'cover', position: 'absolute', inset: 0 }}
              />
              {p.badges?.[0] && (
                <span className="pill accent" style={{ position: 'absolute', top: 24, left: 24, height: 30, padding: '0 14px', fontSize: 12, zIndex: 1 }}>{p.badges[0]}</span>
              )}
              <span className="mono" style={{ position: 'absolute', bottom: 24, left: 24, fontSize: 11, color: 'rgba(255,255,255,.85)', letterSpacing: '0.06em', zIndex: 1, textShadow: '0 1px 2px rgba(0,0,0,.4)' }}>
                {p.id.toUpperCase()}
              </span>
            </div>

            {/* Allergens */}
            <div className="card" style={{ padding: 24, marginTop: 16 }}>
              <span className="eyebrow">Allergens</span>
              <div className="row gap-8" style={{ marginTop: 12, flexWrap: 'wrap' }}>
                {p.allergens?.map(a => <span key={a} className="pill" style={{ background: 'var(--accent-soft)', color: 'var(--accent)', borderColor: 'transparent' }}>{a}</span>)}
              </div>
              {p.mayContain?.length > 0 && (
                <>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 16, letterSpacing: '0.06em', textTransform: 'uppercase' }}>May contain</div>
                  <div className="row gap-8" style={{ marginTop: 8, flexWrap: 'wrap' }}>
                    {p.mayContain.map(a => <span key={a} className="pill">{a}</span>)}
                  </div>
                </>
              )}
              <p style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 16, marginBottom: 0 }}>
                Prepared in kitchens that handle all 14 named allergens. We can't guarantee your meal is allergen-free even after ingredients are removed on request.
              </p>
            </div>
          </div>

          {/* Right — info */}
          <div>
            {p.badges?.[0] && <span className="eyebrow" style={{ color: 'var(--accent)' }}>{p.badges[0]}</span>}
            <h1 className="display product-h1" style={{ fontSize: 'clamp(40px, 5vw, 64px)', margin: '12px 0 12px' }}>{p.name}</h1>
            <p style={{ fontSize: 18, color: 'var(--ink-2)', margin: '0 0 24px', maxWidth: 460 }}>{p.tagline}</p>

            <div className="row gap-16 product-meta-row" style={{ marginBottom: 32, alignItems: 'baseline' }}>
              <span className="display" style={{ fontSize: 40 }}>£{p.price.toFixed(2)}</span>
              <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>·</span>
              <span className="mono" style={{ fontSize: 14, color: 'var(--ink-2)' }}>{totalCal} kcal</span>
              <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>·</span>
              <span className="mono" style={{ fontSize: 14, color: 'var(--ink-2)' }}>{p.weightG} g</span>
            </div>

            <div style={{ marginBottom: 40 }}>
              <a className="btn btn-primary" href={ORDER_URL} target="_blank" rel="noopener noreferrer"
                 style={{ height: 52, width: '100%', fontSize: 15 }}>
                Order this · £{p.price.toFixed(2)}
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M7 17L17 7M9 7h8v8"/></svg>
              </a>
            </div>

            {/* Ingredients & per-item calories */}
            <div style={{ marginBottom: 40 }}>
              <div className="row between" style={{ marginBottom: 12 }}>
                <span className="eyebrow">Ingredients · Calorie breakdown</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.ingredients?.length ?? 0} items</span>
              </div>
              <div className="col">
                {p.ingredients?.map((ing, idx) => {
                  const pct = Math.round((ing.cal / totalCal) * 100);
                  return (
                    <div key={idx} className="row gap-16 ingredient-row" style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
                      <div className="ingredient-tile" style={{
                        width: 56, height: 56, borderRadius: 14,
                        background: 'var(--surface-2)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        flexShrink: 0,
                      }}>
                        <IngredientIcon name={ing.name} color={ing.color} size={40} />
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="row between" style={{ alignItems: 'baseline' }}>
                          <span style={{ fontSize: 15, fontWeight: 600 }}>{ing.name}</span>
                          <span className="mono" style={{ fontSize: 13, color: 'var(--ink-2)', flexShrink: 0, marginLeft: 12 }}>{ing.cal} kcal</span>
                        </div>
                        {ing.notes && (
                          <p className="muted" style={{ margin: '4px 0 8px', fontSize: 12 }}>{ing.notes}</p>
                        )}
                        <div style={{ height: 3, background: 'var(--surface-2)', borderRadius: 2, marginTop: ing.notes ? 0 : 8, overflow: 'hidden' }}>
                          <div style={{ width: `${pct}%`, height: '100%', background: ing.color }} />
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Nutrition table */}
            <div className="card nutrition-card" style={{ padding: 28 }}>
              <div className="row between" style={{ marginBottom: 4 }}>
                <span className="eyebrow">Nutrition · per item</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.weightG}g serving</span>
              </div>
              <div className="row gap-24 nutrition-energy" style={{ padding: '20px 0', borderBottom: '1px solid var(--line)' }}>
                <div className="col">
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>ENERGY</span>
                  <span className="display" style={{ fontSize: 36, marginTop: 4 }}>{p.nutrition?.energyKcal}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>kcal · {p.nutrition?.energyKj} kJ</span>
                </div>
                <div className="col" style={{ flex: 1, paddingLeft: 24, borderLeft: '1px solid var(--line)' }}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>% OF DAILY REFERENCE INTAKE</span>
                  <span className="display" style={{ fontSize: 36, marginTop: 4 }}>{Math.round((p.nutrition?.energyKcal / 2000) * 100)}<span style={{ fontSize: 16, color: 'var(--ink-3)' }}>%</span></span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>based on 2000 kcal</span>
                </div>
              </div>
              {p.nutrition && (
                <>
                  <NutritionBar label="Fat" value={p.nutrition.fat} unit="g" pct={Math.round(p.nutrition.fat / RI.fat * 100)} ri="70g" />
                  <NutritionBar label="of which saturates" value={p.nutrition.satFat} unit="g" pct={Math.round(p.nutrition.satFat / RI.satFat * 100)} ri="20g" />
                  <NutritionBar label="Carbohydrates" value={p.nutrition.carbs} unit="g" pct={Math.round(p.nutrition.carbs / RI.carbs * 100)} ri="260g" />
                  <NutritionBar label="of which sugars" value={p.nutrition.sugars} unit="g" pct={Math.round(p.nutrition.sugars / RI.sugars * 100)} ri="90g" />
                  <NutritionBar label="Fibre" value={p.nutrition.fibre} unit="g" pct={Math.round(p.nutrition.fibre / 30 * 100)} ri="30g" />
                  <NutritionBar label="Protein" value={p.nutrition.protein} unit="g" pct={Math.round(p.nutrition.protein / RI.protein * 100)} ri="50g" />
                  <NutritionBar label="Salt" value={p.nutrition.salt} unit="g" pct={Math.round(p.nutrition.salt / RI.salt * 100)} ri="6g" />
                </>
              )}
            </div>
          </div>
        </div>
      </section>
      <Footer />
    </>
  );
};

Object.assign(window, { ProductPage });
