/* ============ JE BAR — DIY builder screen ============ */

function CakeVisual({ sel }) {
  const { diyColorHex } = window.JEBAR;
  const hex = diyColorHex(sel.color);
  const n = sel.tiers === 't3' ? 3 : sel.tiers === 't2' ? 2 : 1;
  const theme = sel.theme || 'min';
  const hasCandle = (sel.extras || []).includes('candle') || (sel.extras || []).includes('spark');
  const uid = React.useMemo(() => 'cv' + Math.random().toString(36).slice(2, 7), []);

  // ---- colour helpers ----
  const rgb = (h) => { h = h.replace('#', ''); return [0, 2, 4].map(i => parseInt(h.substr(i, 2), 16)); };
  const mix = (h, amt, white) => { const c = rgb(h), t = white ? 255 : 0;
    return 'rgb(' + c.map(x => Math.round(x + (t - x) * amt)).join(',') + ')'; };
  const lighten = (h, a) => mix(h, a, true);
  const darken = (h, a) => mix(h, a, false);

  // ---- geometry ----
  const cx = 100;
  const CFG = { 1: [{ w: 124, h: 82 }], 2: [{ w: 136, h: 60 }, { w: 96, h: 56 }],
    3: [{ w: 146, h: 48 }, { w: 108, h: 44 }, { w: 76, h: 42 }] }[n];
  let bottom = 177; const tiers = [];
  CFG.forEach(t => { const top = bottom - t.h; tiers.push(Object.assign({}, t, { top, bottom })); bottom = top; });
  const topTier = tiers[tiers.length - 1];
  const capRy = (w) => Math.max(6, w * 0.12);

  const isChoco = theme === 'drip';
  const frosting = isChoco ? '#8A6149' : lighten(hex, 0.58);
  const frostingTop = isChoco ? '#9C7256' : lighten(hex, 0.72);

  function frostPath(x0, x1, yTop, baseY, bumps, depth) {
    const w = (x1 - x0) / bumps;
    let d = `M${x0} ${yTop} L${x1} ${yTop} L${x1} ${baseY}`;
    for (let i = bumps - 1; i >= 0; i--) { const xm = x0 + w * (i + 0.5), xe = x0 + w * i; d += ` Q${xm} ${baseY + depth} ${xe} ${baseY}`; }
    return d + ` L${x0} ${yTop} Z`;
  }

  // ---- decorations on the top tier ----
  const PAL = { figure: ['#7FB6E8', '#F4A9C0', '#F2C14E'], fruit: ['#E0556A', '#E98A3D', '#C0497A'],
    mac: ['#F4B8C8', '#BFA0E0', '#A8D8C0'], drip: ['#4A3122', '#6B4A35'], flower: ['#FF8FB0', '#FFD15C'], min: ['#E0556A'] };
  const TOPCOL = { straw: '#E0556A', blueb: '#5566B8', mixfruit: '#E98A3D', cherry: '#B82A3C', mac2: '#BFA0E0', chocpiece: '#6B4A35' };
  const decor = [];
  const tt = topTier, ty = tt.top;
  const rxTop = tt.w / 2 - 4, ryTop = capRy(tt.w) * 0.8;
  const toppingSel = sel.topping || [];
  const place = sel.topPlace || 'ring';
  const spots = [-0.3, -0.1, 0.1, 0.3].map(f => cx + f * tt.w * 0.78);

  // ตำแหน่งวางท็อปปิ้งตามโหมดจัดวาง
  function topSpots() {
    if (place === 'center') return [[0, -0.25], [-0.18, 0.3], [0.18, 0.3], [0, 0.75]].map(p => [cx + p[0] * rxTop, ty + p[1] * ryTop]);
    if (place === 'scatter') return [[-0.62, 0.1], [0.55, -0.3], [-0.2, -0.55], [0.18, 0.5], [0.65, 0.4], [-0.55, -0.5], [0, 0]].map(p => [cx + p[0] * rxTop, ty + p[1] * ryTop]);
    return Array.from({ length: 7 }).map((_, k) => { const a = (k / 7) * Math.PI * 2 - Math.PI / 2;
      return [cx + Math.cos(a) * rxTop * 0.78, ty + Math.sin(a) * ryTop * 0.78]; });
  }

  if (toppingSel.length > 0) {
    // ลูกค้าจัดหน้าเอง: วาดท็อปปิ้งตามตำแหน่งที่เลือก
    topSpots().forEach((pt, i) => {
      const tid = toppingSel[i % toppingSel.length];
      const col = TOPCOL[tid] || '#E0556A';
      const r = tid === 'mixfruit' ? 4.6 : tid === 'mac2' ? 4.8 : 4;
      decor.push(<circle key={'tp' + i} cx={pt[0]} cy={pt[1]} r={r} fill={col} stroke="rgba(0,0,0,.12)" strokeWidth="0.5" />);
      decor.push(<circle key={'tph' + i} cx={pt[0] - r * 0.32} cy={pt[1] - r * 0.34} r={r * 0.3} fill="#fff" opacity="0.55" />);
      if (tid === 'straw' || tid === 'cherry')
        decor.push(<line key={'tps' + i} x1={pt[0]} y1={pt[1] - r} x2={pt[0] + 2} y2={pt[1] - r - 4} stroke="#5E7A52" strokeWidth="1.3" strokeLinecap="round" />);
    });
  } else if (theme === 'flower') {
    [-0.2, 0.2].forEach((f, fi) => {
      const px = cx + f * tt.w * 0.7, py = ty - 3;
      for (let p = 0; p < 6; p++) { const a = (p / 6) * Math.PI * 2;
        decor.push(<ellipse key={'fl' + fi + p} cx={px + Math.cos(a) * 4.2} cy={py + Math.sin(a) * 4.2} rx="3.2" ry="2.2"
          transform={`rotate(${a * 57},${px + Math.cos(a) * 4.2},${py + Math.sin(a) * 4.2})`} fill={PAL.flower[0]} opacity="0.95" />); }
      decor.push(<circle key={'fc' + fi} cx={px} cy={py} r="2.8" fill={PAL.flower[1]} />);
      decor.push(<circle key={'fch' + fi} cx={px - 1} cy={py - 1} r="0.9" fill="#fff" opacity="0.7" />);
    });
  } else if (theme === 'min') {
    decor.push(<line key="stem" x1={cx} y1={ty - 12} x2={cx + 3} y2={ty - 6} stroke="#5E7A52" strokeWidth="1.6" strokeLinecap="round" />);
    decor.push(<circle key="cherry" cx={cx} cy={ty - 5} r="5" fill="#E0556A" />);
    decor.push(<circle key="cherryH" cx={cx - 1.6} cy={ty - 6.6} r="1.4" fill="#fff" opacity="0.6" />);
  } else {
    const pal = PAL[theme] || PAL.figure;
    spots.forEach((sx, i) => {
      const r = theme === 'fruit' ? 4.6 : 4;
      decor.push(<circle key={'d' + i} cx={sx} cy={ty - 2.5} r={r} fill={pal[i % pal.length]}
        stroke="rgba(0,0,0,.1)" strokeWidth="0.5" />);
      decor.push(<circle key={'dh' + i} cx={sx - r * 0.32} cy={ty - 2.5 - r * 0.34} r={r * 0.3} fill="#fff" opacity="0.55" />);
    });
    if (theme === 'figure')
      decor.push(<path key="star" d={`M${cx} ${ty - 16} l2.4 5 5.4.5-4 3.6 1.2 5.3-5-2.8-5 2.8 1.2-5.3-4-3.6 5.4-.5z`} fill="#F2C14E" stroke="#D9A93B" strokeWidth="0.6" />);
  }

  // ---- piping บีบครีมขอบบน ----
  const piping = sel.piping || 'none';
  if (piping !== 'none') {
    const pipCol = isChoco ? '#9C7256' : lighten(hex, 0.5);
    const pipEdge = isChoco ? '#7A573F' : lighten(hex, 0.3);
    const N = 9, rxP = tt.w / 2 - 3, ryP = capRy(tt.w);
    for (let k = 0; k < N; k++) {
      const fx = -1 + 2 * (k + 0.5) / N;
      const px = cx + fx * rxP;
      const py = ty + Math.sqrt(Math.max(0, 1 - fx * fx)) * ryP * 0.92;
      if (piping === 'shell') {
        decor.push(<circle key={'pp' + k} cx={px} cy={py} r="3.6" fill={pipCol} stroke={pipEdge} strokeWidth="0.6" />);
        decor.push(<circle key={'pph' + k} cx={px - 1} cy={py - 1.1} r="1.1" fill="#fff" opacity="0.5" />);
      } else if (piping === 'star') {
        decor.push(<path key={'pp' + k} d={`M${px} ${py - 3.8} L${px + 1.2} ${py - 1.2} L${px + 3.8} ${py} L${px + 1.2} ${py + 1.2} L${px} ${py + 3.8} L${px - 1.2} ${py + 1.2} L${px - 3.8} ${py} L${px - 1.2} ${py - 1.2} Z`} fill={pipCol} stroke={pipEdge} strokeWidth="0.5" />);
      } else {
        decor.push(<ellipse key={'pp' + k} cx={px} cy={py} rx="2.8" ry="3.6" fill={pipCol} stroke={pipEdge} strokeWidth="0.5" />);
        decor.push(<ellipse key={'pph' + k} cx={px - 0.8} cy={py - 1.2} rx="0.9" ry="1.3" fill="#fff" opacity="0.5" />);
      }
    }
  }

  return (
    <div className="cake-vis">
      <svg viewBox="0 0 200 200" width="100%" height="100%" preserveAspectRatio="xMidYMid meet"
        style={{ display: 'block', overflow: 'visible' }}>
        <defs>
          <radialGradient id={uid + 'flame'} cx="50%" cy="35%" r="65%">
            <stop offset="0%" stopColor="#FFF6C8" /><stop offset="55%" stopColor="#FFC24B" /><stop offset="100%" stopColor="#FF7A3D" />
          </radialGradient>
        </defs>

        {/* soft contact shadow */}
        <ellipse cx={cx + 2} cy="186" rx="74" ry="8.5" fill="rgba(46,27,24,.13)" />

        {/* plate */}
        <ellipse cx={cx} cy="182" rx="92" ry="12.5" fill="#F4E7D6" stroke="#E2D0BC" strokeWidth="1" />
        <ellipse cx={cx} cy="179.5" rx="72" ry="8" fill="#fff" opacity="0.55" />
        <path d={`M${cx - 70} 180 Q${cx} 173 ${cx + 70} 180`} fill="none" stroke="#fff" strokeWidth="1.4" opacity="0.6" strokeLinecap="round" />

        {tiers.map((t, i) => {
          const x0 = cx - t.w / 2, x1 = cx + t.w / 2, ry = capRy(t.w);
          const baseY = t.top + t.h * 0.36;
          const fillLineY = t.top + t.h * 0.62;
          return (
            <g key={i}>
              {/* sponge body */}
              <path d={`M${x0} ${t.top} L${x0} ${t.bottom - ry * 0.5} Q${x0} ${t.bottom} ${cx} ${t.bottom} Q${x1} ${t.bottom} ${x1} ${t.bottom - ry * 0.5} L${x1} ${t.top} Z`} fill={hex} />
              {/* upper-left light + lower-right shade */}
              <path d={`M${x0} ${t.top} L${x0} ${t.bottom - ry * 0.5} Q${x0} ${t.bottom} ${cx} ${t.bottom} L${cx} ${t.top} Z`} fill={lighten(hex, 0.16)} opacity="0.5" />
              {/* cream filling line (real sponge layers) */}
              <path d={`M${x0 + 1} ${fillLineY} Q${cx} ${fillLineY + 3.5} ${x1 - 1} ${fillLineY}`} fill="none"
                stroke={lighten(hex, 0.66)} strokeWidth="4.5" strokeLinecap="round" opacity="0.92" />
              <path d={`M${x0 + 1} ${fillLineY} Q${cx} ${fillLineY + 3.5} ${x1 - 1} ${fillLineY}`} fill="none"
                stroke={darken(hex, 0.06)} strokeWidth="0.7" opacity="0.4" />
              {/* base form shading */}
              <ellipse cx={cx} cy={t.bottom - ry * 0.5} rx={t.w / 2} ry={ry} fill={darken(hex, 0.18)} opacity="0.5" />
              {/* left soft highlight */}
              <path d={`M${x0 + 4} ${t.top + 4} Q${x0 + 2} ${t.bottom - 6} ${x0 + 9} ${t.bottom - 8}`} fill="none"
                stroke="#fff" strokeWidth="5" opacity="0.13" strokeLinecap="round" />
              {/* frosting drips */}
              <path d={frostPath(x0 + 1, x1 - 1, t.top - ry * 0.4, baseY, n === 3 ? 6 : 7, 9.5)} fill={frosting} />
              {/* frosting top cap */}
              <ellipse cx={cx} cy={t.top} rx={t.w / 2 - 1} ry={ry} fill={frostingTop} />
              <ellipse cx={cx} cy={t.top - ry * 0.02} rx={t.w / 2 - 1} ry={ry} fill="none" stroke={darken(frosting, 0.06)} strokeWidth="0.6" opacity="0.5" />
              {/* glossy highlight on cap */}
              <ellipse cx={cx - t.w * 0.12} cy={t.top - ry * 0.34} rx={t.w / 2 - 9} ry={ry * 0.5} fill="#fff" opacity="0.34" />
              <ellipse cx={cx + t.w * 0.16} cy={t.top - ry * 0.1} rx={t.w * 0.1} ry={ry * 0.28} fill="#fff" opacity="0.2" />
            </g>
          );
        })}

        {/* candle */}
        {hasCandle && (
          <g>
            <ellipse cx={cx} cy={ty - 3.5} rx="4" ry="1.6" fill="rgba(0,0,0,.12)" />
            <rect x={cx - 2.5} y={ty - 26} width="5" height="22" rx="2.2" fill="#FCE7B0" stroke="#E9C879" strokeWidth="0.8" />
            <rect x={cx - 2.5} y={ty - 26} width="1.6" height="22" rx="1" fill="#fff" opacity="0.5" />
            <rect x={cx - 2.5} y={ty - 20} width="5" height="3.4" fill="#E06A8A" opacity="0.9" />
            <rect x={cx - 2.5} y={ty - 13} width="5" height="3.4" fill="#E06A8A" opacity="0.9" />
            <path d={`M${cx} ${ty - 37} C${cx + 6} ${ty - 31} ${cx + 3.5} ${ty - 25.5} ${cx} ${ty - 25.5} C${cx - 3.5} ${ty - 25.5} ${cx - 6} ${ty - 31} ${cx} ${ty - 37} Z`} fill={`url(#${uid}flame)`} />
            <ellipse cx={cx} cy={ty - 29} rx="1.3" ry="2.2" fill="#FFF3C4" opacity="0.85" />
          </g>
        )}

        {decor}
      </svg>
    </div>
  );
}

function OptGroup({ group, def, sel, onPick }) {
  return (
    <div className="opt-block">
      <h4><Icon name="ruler" size={18} style={{ color: 'var(--primary)' }} /> {def.label}</h4>
      <div className="hint">{def.hint}</div>
      <div className="opt-grid">
        {def.options.map(o => {
          const active = def.kind === 'many'
            ? (sel[group] || []).includes(o.id)
            : sel[group] === o.id;
          if (def.kind === 'color') {
            return (
              <button key={o.id} className={'opt' + (active ? ' on' : '')} onClick={() => onPick(group, o.id, def.kind)}>
                <span className="dot" style={{ width: 26, height: 26, borderRadius: '50%', background: o.hex,
                  boxShadow: 'inset 0 0 0 2px rgba(255,255,255,.6), 0 2px 5px rgba(0,0,0,.15)' }} />
                <span className="nm" style={{ marginTop: 4 }}>{o.nm}</span>
              </button>
            );
          }
          return (
            <button key={o.id} className={'opt' + (active ? ' on' : '')} onClick={() => onPick(group, o.id, def.kind)}>
              <span className="nm">{o.nm}</span>
              {o.sub && <span className="pr" style={{ color: 'var(--muted)', fontWeight: 600 }}>{o.sub}</span>}
              <span className="pr">{o.add > 0 ? '+' + window.JEBAR.formatMoney(o.add, 'symbol') : 'รวมแล้ว'}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function OrderChoiceGroup({ step, title, hint, options, value, values, onPick, many }) {
  return (
    <section className="opt-block" style={{ marginBottom: 30 }}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 12 }}>
        <span style={{ width: 30, height: 30, borderRadius: '50%', display: 'grid', placeItems: 'center',
          flexShrink: 0, background: 'var(--brand)', color: '#fff', fontWeight: 800, fontSize: 14 }}>{step}</span>
        <div>
          <h2 style={{ fontSize: 20, lineHeight: 1.25 }}>{title}</h2>
          <p className="muted" style={{ fontSize: 13.5, marginTop: 3 }}>{hint}</p>
        </div>
      </div>
      <div className="opt-grid" style={{ gridTemplateColumns: 'repeat(auto-fill,minmax(150px,1fr))' }}>
        {options.map(o => {
          const active = many ? (values || []).includes(o.id) : value === o.id;
          return (
            <button key={o.id} type="button" className={'opt' + (active ? ' on' : '')}
              onClick={() => onPick(o.id)} style={{ minHeight: 92 }}>
              <span className="nm">{o.name}</span>
              {o.sub && <span className="pr" style={{ color: 'var(--muted)', fontWeight: 600 }}>{o.sub}</span>}
              <span className="pr">{o.price > 0 ? (o.base ? window.JEBAR.formatMoney(o.price, 'symbol') : '+' + window.JEBAR.formatMoney(o.price, 'symbol')) : 'รวมในราคาฐาน'}</span>
            </button>
          );
        })}
      </div>
    </section>
  );
}

function DiyScreen({ fmt, onContinue, seed, onSeedUsed }) {
  const { formatMoney } = window.JEBAR;
  const [settings, setSettings] = React.useState(() => window.JEBAR_DIY.normalize());
  React.useEffect(() => { let alive = true; window.JEBAR_DIY.load().then(data => { if (alive) setSettings(data); }); return () => { alive = false; }; }, []);
  const SIZE_OPTIONS = settings.groups.size.options;
  const FLAVOR_OPTIONS = settings.groups.flavor.options;
  const FRUIT_OPTIONS = settings.groups.fruit.options;
  const DESIGN_OPTIONS = settings.groups.design.options;
  const CREAM_OPTIONS = settings.groups.cream.options;
  const COLORS = settings.colors;

  const initialDesign = seed && seed.theme === 'figure' ? ['model']
    : seed && seed.theme === 'drip' ? ['drip']
    : seed && seed.theme === 'fruit' ? ['fruit_front'] : ['minimal'];
  const [order, setOrder] = React.useState({
    size: seed && SIZE_OPTIONS.some(x => x.id === seed.size) ? seed.size : '1lb',
    flavor: seed && seed.sponge === 'ch' ? 'chocolate' : 'vanilla',
    fruit: seed && seed.theme === 'fruit' ? 'mixed' : 'none',
    designs: initialDesign,
    cream: 'non_dairy',
    color: seed && seed.color ? seed.color : 'pink'
  });
  React.useEffect(() => {
    setOrder(prev => {
      const validDesigns = prev.designs.filter(id => DESIGN_OPTIONS.some(item => item.id === id));
      return {
        ...prev,
        size: SIZE_OPTIONS.some(item => item.id === prev.size) ? prev.size : SIZE_OPTIONS[0].id,
        flavor: FLAVOR_OPTIONS.some(item => item.id === prev.flavor) ? prev.flavor : FLAVOR_OPTIONS[0].id,
        fruit: FRUIT_OPTIONS.some(item => item.id === prev.fruit) ? prev.fruit : FRUIT_OPTIONS[0].id,
        designs: validDesigns.length ? validDesigns : [DESIGN_OPTIONS[0].id],
        cream: CREAM_OPTIONS.some(item => item.id === prev.cream) ? prev.cream : CREAM_OPTIONS[0].id,
        color: COLORS.some(item => item.id === prev.color) ? prev.color : COLORS[0].id
      };
    });
  }, [settings]);
  const [message, setMessage] = React.useState('');
  const [note, setNote] = React.useState('');
  React.useEffect(() => { if (seed && onSeedUsed) onSeedUsed(); }, []);

  const size = SIZE_OPTIONS.find(x => x.id === order.size) || SIZE_OPTIONS[0];
  const flavor = FLAVOR_OPTIONS.find(x => x.id === order.flavor) || FLAVOR_OPTIONS[0];
  const fruit = FRUIT_OPTIONS.find(x => x.id === order.fruit) || FRUIT_OPTIONS[0];
  const cream = CREAM_OPTIONS.find(x => x.id === order.cream) || CREAM_OPTIONS[0];
  const selectedDesigns = DESIGN_OPTIONS.filter(x => order.designs.includes(x.id));
  const creamPrice = cream.perPound ? size.pounds * cream.price : cream.price;
  const total = size.price + fruit.price + creamPrice + selectedDesigns.reduce((sum, x) => sum + x.price, 0);

  function toggleDesign(id) {
    setOrder(prev => {
      let next = prev.designs.includes(id) ? prev.designs.filter(x => x !== id) : [...prev.designs, id];
      if (id === 'minimal' && !prev.designs.includes(id)) next = ['minimal'];
      else if (id !== 'minimal') next = next.filter(x => x !== 'minimal');
      if (!next.length) next = [DESIGN_OPTIONS[0].id];
      return { ...prev, designs: next };
    });
  }


  const theme = order.designs.includes('model') ? 'figure'
    : order.designs.includes('drip') ? 'drip'
    : (order.fruit !== 'none' || order.designs.includes('fruit_front')) ? 'fruit' : 'min';
  const toppingMap = { strawberry: 'straw', blueberry: 'blueb', orange: 'mixfruit', mango: 'mixfruit', mixed: 'mixfruit' };
  const visual = {
    size: order.size, tiers: 't1', sponge: order.flavor === 'chocolate' ? 'ch' : 'va',
    cream: order.cream === 'dairy' ? 'wc' : 'bc', theme, color: order.color,
    plate: 'none', extras: [], filling: [], piping: 'none', topPlace: 'ring',
    topping: order.fruit === 'none' ? [] : [toppingMap[order.fruit] || 'mixfruit'],
    orderSheet: { ...order, message, note }
  };

  const rows = [
    { label: size.name, value: size.price },
    ...(fruit.price ? [{ label: fruit.name, value: fruit.price }] : []),
    ...selectedDesigns.filter(x => x.price).map(x => ({ label: x.name, value: x.price })),
    ...(creamPrice ? [{ label: cream.name + ' (' + size.pounds + ' ปอนด์)', value: creamPrice }] : [])
  ];
  const detail = [size.name, flavor.name, fruit.name, selectedDesigns.map(x => x.name).join(', '), cream.name]
    .filter(Boolean).join(' · ') + (message ? ' · “' + message + '”' : '') + (note ? ' · ' + note : '');
  const joSummary = [
    'สรุปแบบเค้กจากหน้าออกแบบเอง',
    '- ขนาด: ' + size.name,
    '- รสเค้ก: ' + flavor.name,
    '- ผลไม้: ' + fruit.name,
    '- แบบตกแต่ง: ' + (selectedDesigns.map(x => x.name).join(', ') || 'ยังไม่ระบุ'),
    '- ครีม: ' + cream.name,
    '- โทนสี: ' + ((COLORS.find(x => x.id === order.color) || {}).name || order.color),
    message ? '- ข้อความบนเค้ก: ' + message : '',
    note ? '- รายละเอียดเพิ่มเติม: ' + note : '',
    '- ราคาประเมินเบื้องต้น: ' + formatMoney(total, fmt),
    'ช่วยรับช่วงสอบถามรายละเอียดที่ยังขาด และยืนยันราคาจริงกับลูกค้าต่อค่ะ'
  ].filter(Boolean).join('\n');

  return (
    <main className="section order-sheet">
      <div className="wrap">
        <div style={{ marginBottom: 28 }}>
          <span className="eyebrow">{settings.page.eyebrow}</span>
          <h1 style={{ fontSize: 'clamp(30px,4vw,46px)', marginTop: 12 }}>{settings.page.title}</h1>
          <p className="muted" style={{ marginTop: 8, fontSize: 16 }}>{settings.page.subtitle}</p>
          <div className="demo-note">
            <Icon name="spark" size={18} style={{ flexShrink: 0, marginTop: 1 }} />
            <span><b>ราคาประเมินเบื้องต้น</b> {settings.page.notice}</span>
          </div>
        </div>

        <div className="builder">
          <div>
            <OrderChoiceGroup {...settings.groups.size} options={SIZE_OPTIONS}
              value={order.size} onPick={id => setOrder({ ...order, size: id })} />
            <OrderChoiceGroup {...settings.groups.flavor} options={FLAVOR_OPTIONS}
              value={order.flavor} onPick={id => setOrder({ ...order, flavor: id })} />
            <OrderChoiceGroup {...settings.groups.fruit} options={FRUIT_OPTIONS}
              value={order.fruit} onPick={id => setOrder({ ...order, fruit: id })} />
            <OrderChoiceGroup {...settings.groups.design} options={DESIGN_OPTIONS}
              values={order.designs} onPick={toggleDesign} many />

            <section className="opt-block" style={{ marginBottom: 30 }}>
              <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 12 }}>
                <span style={{ width: 30, height: 30, borderRadius: '50%', display: 'grid', placeItems: 'center',
                  flexShrink: 0, background: 'var(--brand)', color: '#fff', fontWeight: 800, fontSize: 14 }}>3.1</span>
                <div><h2 style={{ fontSize: 20 }}>เลือกโทนสี</h2><p className="muted" style={{ fontSize: 13.5, marginTop: 3 }}>สีหลักของครีมและภาพร่าง</p></div>
              </div>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                {COLORS.map(c => <button key={c.id} type="button" onClick={() => setOrder({ ...order, color: c.id })}
                  title={c.name} aria-label={c.name} style={{ width: 42, height: 42, borderRadius: '50%', cursor: 'pointer', background: c.hex,
                    border: order.color === c.id ? '3px solid var(--brand)' : '3px solid #fff', boxShadow: '0 0 0 1px var(--line)' }} />)}
              </div>
            </section>

            <OrderChoiceGroup {...settings.groups.cream} options={CREAM_OPTIONS}
              value={order.cream} onPick={id => setOrder({ ...order, cream: id })} />

            <section className="opt-block">
              <h2 style={{ fontSize: 20, marginBottom: 10 }}>ข้อความบนเค้กและรายละเอียดเพิ่มเติม</h2>
              <input className="input" value={message} maxLength={60} onChange={e => setMessage(e.target.value)}
                placeholder="ข้อความบนเค้ก เช่น Happy Birthday น้องเจ" />
              <textarea className="input" rows={4} value={note} onChange={e => setNote(e.target.value)}
                placeholder="ระบุสี รูปการ์ตูน จำนวนตัวอย่าง หรือรายละเอียดที่ต้องการ" style={{ marginTop: 10, resize: 'vertical' }} />
            </section>
          </div>

          <aside className="summary">
            <div className="summary__art">
              <CakeVisual sel={visual} />
              <span style={{ position: 'absolute', top: 10, left: 12, fontSize: 11, fontWeight: 800,
                background: 'rgba(255,255,255,.9)', padding: '5px 9px', borderRadius: 999 }}>ภาพร่างตามที่เลือก</span>
            </div>
            <div className="summary__body">
              <h3 style={{ fontSize: 21 }}>สรุปเค้กของคุณ</h3>
              <div style={{ marginTop: 12 }}>
                {rows.map((row, i) => <div className="line" key={i}><span className="l">{row.label}</span><span className="v">{formatMoney(row.value, fmt)}</span></div>)}
                <div className="line"><span className="l">รสเค้ก</span><span className="v">{flavor.name}</span></div>
                <div className="line"><span className="l">ครีม</span><span className="v">{cream.name}</span></div>
              </div>
              <div className="total"><span className="muted" style={{ fontWeight: 700 }}>ราคาประเมิน</span><span className="big">{formatMoney(total, fmt)}</span></div>
              <button className="btn btn--primary btn--lg" style={{ width: '100%', marginTop: 14 }}
                onClick={() => onContinue({ kind: 'diy-summary', text: joSummary, detail, total, visual })}>
                {window.joOn && !window.joOn()
                  ? <><Icon name="chat" size={20} /> ส่งแบบนี้ให้ร้านทาง LINE</>
                  : <><Icon name="spark" size={20} /> ส่งแบบให้โจรับช่วงต่อ</>}
              </button>
              <p className="muted center" style={{ fontSize: 12, marginTop: 10 }}>ร้านจะตรวจแบบ วัตถุดิบตามฤดูกาล และยืนยันราคาสุดท้ายอีกครั้ง</p>
            </div>
          </aside>
        </div>
      </div>
    </main>
  );
}
Object.assign(window, { DiyScreen, CakeVisual });
