// v-menu.jsx — Menu Manager: item table + health score + recommendations

const MARGIN_TONE = { high:{tone:'green',label:'High'}, med:{tone:'amber',label:'Medium'}, low:{tone:'red',label:'Low'} };

function MenuRow({ it, app, onOpen, last }) {
  const m = MARGIN_TONE[it.margin];
  return (
    <div onClick={()=>onOpen(it)} style={{ display:'grid', gridTemplateColumns:'2.4fr 0.8fr 1fr 1.3fr 0.9fr 1fr 1fr 1.1fr', alignItems:'center', gap:10, padding:'12px 18px', cursor:'pointer',
      borderBottom: last?'none':'1px solid var(--soft-line)', opacity: it.avail?1:0.62, transition:'background 150ms' }}
      onMouseEnter={(e)=>e.currentTarget.style.background='var(--bg-elevated)'} onMouseLeave={(e)=>e.currentTarget.style.background='transparent'}>
      {/* name + photo */}
      <div style={{ display:'flex', alignItems:'center', gap:11, minWidth:0 }}>
        <div style={{ width:38, height:38, borderRadius:9, flexShrink:0, overflow:'hidden', position:'relative', background: it.photoUrl?'#000': it.photo?'linear-gradient(135deg,#E8956A,#C24A1E)':'repeating-linear-gradient(135deg,#EDE3D6,#EDE3D6 5px,#E3D7C6 5px,#E3D7C6 10px)', display:'flex', alignItems:'center', justifyContent:'center' }}>
          {it.photoUrl ? <img src={it.photoUrl} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }}/> : !it.photo && <I.image c="#B6A595" s={16}/>}
        </div>
        <div style={{ minWidth:0 }}>
          <div style={{ display:'flex', alignItems:'center', gap:7 }}>
            <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13.5, color:'var(--fg-primary)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{it.name}</span>
            {it.best && <Pill tone="orange" icon={<I.flame c="#c0500f" s={10} f/>} style={{ fontSize:9.5, padding:'2px 6px' }}>Best seller</Pill>}
            {it.isNew && <Pill tone="blue" style={{ fontSize:9.5, padding:'2px 6px' }}>New</Pill>}
          </div>
          <span style={{ fontFamily:'var(--font-mono)', fontSize:10.5, color:'var(--warm-stone)' }}>{it.id.toUpperCase()}</span>
        </div>
      </div>
      {/* price */}
      <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13.5, color:'var(--fg-primary)' }}>£{it.price.toFixed(2)}</div>
      {/* availability */}
      <div>{it.avail ? <Pill tone="green" dot>Available</Pill> : <Pill tone="red" dot>Off</Pill>}</div>
      {/* popularity */}
      <div style={{ display:'flex', alignItems:'center', gap:8 }}>
        <div style={{ flex:1, maxWidth:54 }}><Bar pct={it.pop} color={it.pop>80?'#2E8B4E':it.pop>55?'#E0992A':'#C13B1F'} h={6}/></div>
        <span style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:12, color:'var(--warm-stone)', width:22 }}>{it.pop}</span>
      </div>
      {/* margin */}
      <div><Pill tone={m.tone}>{m.label}</Pill></div>
      {/* photo */}
      <div>{it.photo ? <span style={{ display:'inline-flex', alignItems:'center', gap:5, fontFamily:'var(--font-body)', fontSize:12, color:'#247a41' }}><I.check c="#247a41" s={14}/>Photo</span> : <span style={{ display:'inline-flex', alignItems:'center', gap:5, fontFamily:'var(--font-body)', fontSize:12, color:'#b0341a' }}><I.alert c="#b0341a" s={13}/>Missing</span>}</div>
      {/* modifiers */}
      <div>
        {it.mods==='full' && <span style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--fg-primary)' }}>Full</span>}
        {it.mods==='partial' && <span style={{ fontFamily:'var(--font-body)', fontSize:12, color:'#a86d12' }}>Partial</span>}
        {it.mods==='none' && <span style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)' }}>None</span>}
      </div>
      {/* trend + promote */}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'flex-end', gap:10 }}>
        <Trend dir={it.trendDir} pct={it.trendPct} size={12}/>
        <button onClick={(e)=>{ e.stopPropagation(); app.openBuilder(null, it); }} title="Promote into a campaign" style={{ width:30, height:30, borderRadius:9, border:'1px solid var(--soft-line)', background:'var(--bg-surface)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
          <I.rocket c="var(--brand-orange)" s={15}/>
        </button>
        <I.chevR c="var(--warm-stone)" s={16}/>
      </div>
    </div>
  );
}

// ─── Add-item editor (full controls) ─────────────────────────────────
function MSeg({ label, options, value, onChange }) {
  return (
    <div>
      <div style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--warm-stone)', marginBottom:7 }}>{label}</div>
      <div style={{ display:'flex', gap:6 }}>
        {options.map(o=>{
          const on = o.value===value;
          return <button key={o.value} onClick={()=>onChange(o.value)} style={{ flex:1, padding:'9px 8px', borderRadius:9, cursor:'pointer',
            background: on?'var(--dark-chocolate)':'var(--bg-app)', color: on?'var(--dust-cream)':'var(--fg-primary)', border:'1px solid', borderColor: on?'var(--dark-chocolate)':'var(--soft-line)',
            fontFamily:'var(--font-display)', fontWeight:700, fontSize:12 }}>{o.label}</button>;
        })}
      </div>
    </div>
  );
}

const FLD_LABEL = { fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--warm-stone)', marginBottom:7, display:'block' };
const FLD_INPUT = { width:'100%', boxSizing:'border-box', background:'var(--bg-app)', border:'1px solid var(--soft-line)', borderRadius:9, padding:'10px 12px', fontFamily:'var(--font-body)', fontSize:13.5, color:'var(--fg-primary)', outline:'none' };

// Build-your-own presets — instant scaffolds the vendor can then edit
const BYO_TEMPLATES = {
  pizza: { groups:[
    { n:'Size',           s:'one', r:true,  o:[['10\" personal',0],['12\" classic',2.5],['14\" sharing',4]] },
    { n:'Base & crust',   s:'one', r:true,  o:[['Classic',0],['Stuffed crust',2],['Gluten-free',1.5]] },
    { n:'Sauce',          s:'one', r:false, o:[['Tomato',0],['BBQ',0],['Garlic base',0.5]] },
    { n:'Extra toppings', s:'any', r:false, max:6, o:[['Pepperoni',1.5],['Mushrooms',1],['Nduja',2],['Extra cheese',1.5],['Jalapeños',1],['Red onion',0.8]] },
  ]},
  burger: { groups:[
    { n:'Patty',          s:'one', r:true,  o:[['Single',0],['Double',3]] },
    { n:'Cheese',         s:'one', r:false, o:[['American',0.8],['Cheddar',0.8],['No cheese',0]] },
    { n:'Toppings',       s:'any', r:false, o:[['Bacon',1.5],['Avocado',1.5],['Fried egg',1.2],['Caramelised onion',1]] },
    { n:'Sauce',          s:'any', r:false, max:2, o:[['Burger sauce',0],['BBQ',0],['Sriracha mayo',0.5]] },
    { n:'Make it a meal', s:'one', r:false, o:[['Just the burger',0],['Add fries',3],['Fries & drink',5]] },
  ]},
};

const byoUid = ()=> Math.random().toString(36).slice(2,8);

// ─── Modifier-group editor (size / toppings / sauces …) ──────────────
function ModGroupEditor({ groups, setGroups }) {
  const patchG=(id,p)=>setGroups(gs=>gs.map(g=>g.id===id?{...g,...p}:g));
  const patchO=(gid,oid,p)=>setGroups(gs=>gs.map(g=>g.id!==gid?g:{...g,options:g.options.map(o=>o.id===oid?{...o,...p}:o)}));
  const addOpt=(gid)=>setGroups(gs=>gs.map(g=>g.id!==gid?g:{...g,options:[...g.options,{id:byoUid(),name:'',price:0}]}));
  const delOpt=(gid,oid)=>setGroups(gs=>gs.map(g=>g.id!==gid?g:{...g,options:g.options.filter(o=>o.id!==oid)}));
  const delGroup=(id)=>setGroups(gs=>gs.filter(g=>g.id!==id));
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
      {groups.map((g,gi)=>(
        <div key={g.id} style={{ border:'1px solid var(--soft-line)', borderRadius:13, padding:'13px 14px', background:'var(--bg-app)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:9, marginBottom:11 }}>
            <span style={{ width:20, height:20, flexShrink:0, borderRadius:6, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'var(--font-mono)', fontSize:10.5, color:'var(--horse-brown)' }}>{gi+1}</span>
            <input value={g.name} onChange={e=>patchG(g.id,{name:e.target.value})} placeholder="Group name — e.g. Size, Toppings" maxLength={28} style={{ ...FLD_INPUT, flex:1, padding:'8px 11px', fontFamily:'var(--font-display)', fontWeight:700, fontSize:13 }}/>
            <button onClick={()=>delGroup(g.id)} title="Remove group" style={{ width:30, height:30, borderRadius:8, border:'1px solid var(--soft-line)', background:'var(--bg-surface)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><I.x c="var(--warm-stone)" s={15}/></button>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:11, flexWrap:'wrap' }}>
            <Segmented size="sm" options={[{value:'one',label:'Choose one'},{value:'any',label:'Choose any'}]} value={g.select} onChange={v=>patchG(g.id,{select:v})}/>
            <div onClick={()=>patchG(g.id,{required:!g.required})} role="button" style={{ display:'flex', alignItems:'center', gap:7, cursor:'pointer' }}>
              <Toggle on={g.required} onChange={()=>patchG(g.id,{required:!g.required})}/>
              <span style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--fg-primary)' }}>Required</span>
            </div>
            {g.select==='any' && (
              <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                <span style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)' }}>Max</span>
                <input value={g.max??''} onChange={e=>{const n=e.target.value.replace(/\D/g,'');patchG(g.id,{max:n?Math.max(1,parseInt(n)):null});}} placeholder="∞" style={{ ...FLD_INPUT, width:46, padding:'7px 6px', textAlign:'center' }}/>
              </div>
            )}
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:7 }}>
            {g.options.map(o=>(
              <div key={o.id} style={{ display:'flex', alignItems:'center', gap:8 }}>
                <input value={o.name} onChange={e=>patchO(g.id,o.id,{name:e.target.value})} placeholder="Option name" maxLength={30} style={{ ...FLD_INPUT, flex:1, padding:'8px 11px' }}/>
                <div style={{ position:'relative', width:86, flexShrink:0 }}>
                  <span style={{ position:'absolute', left:9, top:'50%', transform:'translateY(-50%)', fontFamily:'var(--font-display)', fontWeight:700, fontSize:12, color:'var(--warm-stone)' }}>+£</span>
                  <input value={o.price===0?'':o.price} onChange={e=>patchO(g.id,o.id,{price:parseFloat(e.target.value.replace(/[^0-9.]/g,''))||0})} inputMode="decimal" placeholder="0" style={{ ...FLD_INPUT, width:'100%', boxSizing:'border-box', padding:'8px 8px 8px 26px' }}/>
                </div>
                <button onClick={()=>delOpt(g.id,o.id)} title="Remove option" style={{ width:28, height:28, borderRadius:7, border:'1px solid var(--soft-line)', background:'var(--bg-surface)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><I.x c="var(--warm-stone)" s={13}/></button>
              </div>
            ))}
            <button onClick={()=>addOpt(g.id)} style={{ alignSelf:'flex-start', marginTop:2, display:'inline-flex', alignItems:'center', gap:5, background:'none', border:'none', cursor:'pointer', fontFamily:'var(--font-display)', fontWeight:700, fontSize:11.5, color:'var(--brand-orange)' }}><I.plus c="var(--brand-orange)" s={13}/> Add option</button>
          </div>
        </div>
      ))}
    </div>
  );
}

function AddItemModal({ app, onClose, onAdd }) {
  const [name, setName] = React.useState('');
  const [catSel, setCatSel] = React.useState(MENU[0].cat);
  const [newCat, setNewCat] = React.useState('');
  const usingNew = catSel==='__new';
  const [price, setPrice] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [avail, setAvail] = React.useState(true);
  const [margin, setMargin] = React.useState('high');
  const [photoUrl, setPhotoUrl] = React.useState(null);
  const [groups, setGroups] = React.useState([]);
  const fileRef = React.useRef(null);

  const onFile = (e)=>{ const f=e.target.files&&e.target.files[0]; if(!f) return; const r=new FileReader(); r.onload=()=>setPhotoUrl(r.result); r.readAsDataURL(f); };
  const priceNum = parseFloat(price);
  const catName = usingNew ? newCat.trim() : catSel;
  const valid = name.trim().length>0 && priceNum>0 && (!usingNew || newCat.trim().length>0);

  const addGroup=()=>setGroups(gs=>[...gs,{ id:byoUid(), name:'', select:'any', required:false, max:null, options:[{id:byoUid(),name:'',price:0}] }]);
  const applyTemplate=(k)=>setGroups(BYO_TEMPLATES[k].groups.map(g=>({ id:byoUid(), name:g.n, select:g.s, required:!!g.r, max:g.max??null, options:g.o.map(o=>({ id:byoUid(), name:o[0], price:o[1] })) })));

  // build price range from the configured groups
  const basePrice = priceNum>0?priceNum:0;
  const reqAdds = groups.filter(g=>g.required&&g.options.length).reduce((s,g)=>s+Math.min(...g.options.map(o=>+o.price||0)),0);
  const maxAdds = groups.reduce((s,g)=>{
    const ps=g.options.map(o=>+o.price||0); if(!ps.length) return s;
    if(g.select==='one') return s+Math.max(...ps,0);
    const sorted=ps.filter(p=>p>0).sort((a,b)=>b-a); const lim=g.max||sorted.length; return s+sorted.slice(0,lim).reduce((a,b)=>a+b,0);
  },0);
  const optionCount = groups.reduce((s,g)=>s+g.options.filter(o=>o.name.trim()).length,0);

  const save = ()=>{
    if(!valid) return;
    const modGroups = groups.map(g=>({
      name:g.name.trim(), select:g.select, required:!!g.required, max:g.max||null,
      options:g.options.filter(o=>o.name.trim()).map(o=>({ name:o.name.trim(), price:+o.price||0 })),
    })).filter(g=>g.name && g.options.length);
    const mods = modGroups.length===0?'none':modGroups.length>=2?'full':'partial';
    onAdd({
      id: 'm'+Date.now().toString().slice(-5),
      name: name.trim(), price: priceNum, avail, pop:0, margin,
      photo: !!photoUrl, photoUrl: photoUrl||undefined, mods, modGroups,
      trendDir:'flat', trendPct:0, best:false, isNew:true, desc: desc.trim(),
    }, catName);
  };

  const m = MARGIN_TONE[margin];

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:300, background:'rgba(27,18,13,0.46)', backdropFilter:'blur(3px)', display:'flex', justifyContent:'center', alignItems:'flex-start', padding:'34px 22px', overflowY:'auto', animation:'v-fade 200ms' }}>
      <div onClick={(e)=>e.stopPropagation()} style={{ width:'100%', maxWidth:600, background:'var(--bg-surface)', borderRadius:20, boxShadow:'var(--shadow-lg)', overflow:'hidden', animation:'v-pop 240ms var(--ease-out)' }}>
        {/* header */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'16px 22px', borderBottom:'1px solid var(--soft-line)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:11 }}>
            <div style={{ width:36, height:36, borderRadius:10, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center' }}><I.utensils c="var(--brand-orange)" s={18}/></div>
            <div>
              <h2 style={{ margin:0, fontFamily:'var(--font-display)', fontWeight:900, fontSize:18, color:'var(--fg-primary)' }}>Add menu item</h2>
              <div style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)' }}>New dishes go live on Lasso after a quick review</div>
            </div>
          </div>
          <button onClick={onClose} style={{ width:34, height:34, borderRadius:10, border:'1px solid var(--soft-line)', background:'var(--bg-app)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}><I.x c="var(--warm-stone)" s={17}/></button>
        </div>

        <div style={{ padding:'20px 22px', display:'flex', flexDirection:'column', gap:18 }}>
          {/* photo + name + price */}
          <div style={{ display:'flex', gap:16 }}>
            <div>
              <span style={FLD_LABEL}>Photo</span>
              <button onClick={()=>fileRef.current&&fileRef.current.click()} style={{ width:96, height:96, borderRadius:13, cursor:'pointer', overflow:'hidden', position:'relative',
                border: photoUrl?'1px solid var(--soft-line)':'1.5px dashed var(--warm-stone)', background: photoUrl?'#000':'var(--bg-app)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:5, padding:0 }}>
                {photoUrl ? <img src={photoUrl} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }}/> : <><I.image c="var(--warm-stone)" s={22}/><span style={{ fontFamily:'var(--font-body)', fontSize:10.5, color:'var(--warm-stone)' }}>Upload</span></>}
              </button>
              {photoUrl && <button onClick={()=>setPhotoUrl(null)} style={{ marginTop:6, background:'none', border:'none', cursor:'pointer', fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, color:'var(--warm-stone)' }}>Remove</button>}
              <input ref={fileRef} type="file" accept="image/*" onChange={onFile} style={{ display:'none' }}/>
            </div>
            <div style={{ flex:1, minWidth:0, display:'flex', flexDirection:'column', gap:14 }}>
              <div>
                <span style={FLD_LABEL}>Item name</span>
                <input value={name} onChange={(e)=>setName(e.target.value)} placeholder="e.g. Truffle Mushroom Pizza" maxLength={42} style={FLD_INPUT}/>
              </div>
              <div>
                <span style={FLD_LABEL}>Price</span>
                <div style={{ position:'relative' }}>
                  <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', fontFamily:'var(--font-display)', fontWeight:800, fontSize:14, color:'var(--warm-stone)' }}>£</span>
                  <input value={price} onChange={(e)=>setPrice(e.target.value.replace(/[^0-9.]/g,''))} inputMode="decimal" placeholder="0.00" style={{ ...FLD_INPUT, paddingLeft:26 }}/>
                </div>
              </div>
            </div>
          </div>

          {/* category */}
          <div>
            <span style={FLD_LABEL}>Category</span>
            <div style={{ display:'flex', gap:7, flexWrap:'wrap' }}>
              {MENU.map(c=>{
                const on = catSel===c.cat;
                return <button key={c.cat} onClick={()=>setCatSel(c.cat)} style={{ padding:'8px 13px', borderRadius:9, cursor:'pointer',
                  background: on?'var(--dark-chocolate)':'var(--bg-app)', color: on?'var(--dust-cream)':'var(--fg-primary)', border:'1px solid', borderColor: on?'var(--dark-chocolate)':'var(--soft-line)',
                  fontFamily:'var(--font-display)', fontWeight:700, fontSize:12.5 }}>{c.cat}</button>;
              })}
              <button onClick={()=>setCatSel('__new')} style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'8px 13px', borderRadius:9, cursor:'pointer',
                background: usingNew?'var(--brand-orange)':'var(--bg-app)', color: usingNew?'#fff':'var(--brand-orange)', border:'1px solid', borderColor: usingNew?'var(--brand-orange)':'var(--soft-line)',
                fontFamily:'var(--font-display)', fontWeight:700, fontSize:12.5 }}><I.plus c={usingNew?'#fff':'var(--brand-orange)'} s={14}/> New</button>
            </div>
            {usingNew && <input value={newCat} onChange={(e)=>setNewCat(e.target.value)} placeholder="New category name" maxLength={24} style={{ ...FLD_INPUT, marginTop:9 }}/>}
          </div>

          {/* description */}
          <div>
            <span style={FLD_LABEL}>Description <span style={{ textTransform:'none', letterSpacing:0, color:'var(--fg-muted)', fontWeight:400 }}>· optional</span></span>
            <textarea value={desc} onChange={(e)=>setDesc(e.target.value)} placeholder="Short, appetising description customers will read…" maxLength={140} rows={2} style={{ ...FLD_INPUT, resize:'vertical', lineHeight:1.45 }}/>
          </div>

          {/* build-your-own / customisation */}
          <div>
            <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:9, gap:10 }}>
              <span style={FLD_LABEL}>Build-your-own &amp; add-ons</span>
              {optionCount>0 && <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:11.5, color:'var(--brand-orange)', whiteSpace:'nowrap' }}>Build price £{(basePrice+reqAdds).toFixed(2)} – £{(basePrice+maxAdds).toFixed(2)}</span>}
            </div>
            {groups.length===0 ? (
              <div style={{ padding:'16px 15px', border:'1.5px dashed var(--soft-line)', borderRadius:12, textAlign:'center' }}>
                <div style={{ fontFamily:'var(--font-body)', fontSize:12.5, color:'var(--warm-stone)', marginBottom:12, lineHeight:1.45 }}>Let customers customise this dish — sizes, bases, toppings, sauces, make-it-a-meal. Start from a preset, then edit.</div>
                <div style={{ display:'flex', gap:8, justifyContent:'center', flexWrap:'wrap' }}>
                  <Btn kind="white" size="sm" icon={<I.pizza c="var(--brand-orange)" s={14}/>} onClick={()=>applyTemplate('pizza')}>Build-your-own pizza</Btn>
                  <Btn kind="white" size="sm" icon={<I.utensils c="var(--brand-orange)" s={14}/>} onClick={()=>applyTemplate('burger')}>Build-your-own burger</Btn>
                  <Btn kind="white" size="sm" icon={<I.plus c="var(--fg-primary)" s={14}/>} onClick={addGroup}>Blank group</Btn>
                </div>
              </div>
            ) : (
              <div>
                <ModGroupEditor groups={groups} setGroups={setGroups}/>
                <div style={{ display:'flex', gap:8, marginTop:11, flexWrap:'wrap', alignItems:'center' }}>
                  <Btn kind="white" size="sm" icon={<I.plus c="var(--fg-primary)" s={14}/>} onClick={addGroup}>Add group</Btn>
                  <span style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--fg-muted)' }}>Preset:</span>
                  <button onClick={()=>applyTemplate('pizza')} style={{ background:'none', border:'none', cursor:'pointer', fontFamily:'var(--font-display)', fontWeight:700, fontSize:11.5, color:'var(--brand-orange)' }}>Pizza</button>
                  <button onClick={()=>applyTemplate('burger')} style={{ background:'none', border:'none', cursor:'pointer', fontFamily:'var(--font-display)', fontWeight:700, fontSize:11.5, color:'var(--brand-orange)' }}>Burger</button>
                  <button onClick={()=>setGroups([])} style={{ marginLeft:'auto', background:'none', border:'none', cursor:'pointer', fontFamily:'var(--font-display)', fontWeight:700, fontSize:11.5, color:'var(--warm-stone)' }}>Clear all</button>
                </div>
              </div>
            )}
          </div>

          {/* margin */}
          <MSeg label="Profit margin" value={margin} onChange={setMargin} options={[{value:'low',label:'Low'},{value:'med',label:'Medium'},{value:'high',label:'High'}]}/>

          {/* availability */}
          <div onClick={()=>setAvail(v=>!v)} role="button" style={{ display:'flex', alignItems:'center', gap:12, padding:'13px 15px', background:'var(--bg-app)', border:'1px solid var(--soft-line)', borderRadius:12, cursor:'pointer' }}>
            <Toggle on={avail} onChange={()=>setAvail(v=>!v)} color="var(--live-green)"/>
            <div style={{ flex:1 }}>
              <div style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:13, color:'var(--fg-primary)' }}>Available to order</div>
              <div style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>{avail?'Customers can order this right away':'Saved but hidden from the menu'}</div>
            </div>
            {avail ? <Pill tone="green" dot>On</Pill> : <Pill tone="red" dot>Off</Pill>}
          </div>
        </div>

        {/* footer */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:14, padding:'15px 22px', borderTop:'1px solid var(--soft-line)', background:'var(--bg-app)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:9, minWidth:0 }}>
            <div style={{ width:34, height:34, borderRadius:8, flexShrink:0, overflow:'hidden', background: photoUrl?'#000':'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center' }}>{photoUrl?<img src={photoUrl} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }}/>:<I.utensils c="var(--brand-orange)" s={15}/>}</div>
            <div style={{ minWidth:0 }}>
              <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13, color:'var(--fg-primary)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{name.trim()||'New item'}</div>
              <div style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>{priceNum>0?`£${priceNum.toFixed(2)}`:'£0.00'} · {catName||'No category'}{optionCount>0?` · ${optionCount} options`:''} · <span style={{ color: m.tone==='green'?'#247a41':m.tone==='amber'?'#a86d12':'#b0341a' }}>{m.label} margin</span></div>
            </div>
          </div>
          <div style={{ display:'flex', gap:10, flexShrink:0 }}>
            <Btn kind="white" onClick={onClose}>Cancel</Btn>
            <Btn kind="accent" icon={<I.check c="#fff" s={16}/>} disabled={!valid} onClick={save}>Add item</Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

function MenuScreen({ app }) {
  const [cat, setCat] = React.useState('All');
  const [adding, setAdding] = React.useState(false);
  const [view, setView] = React.useState('items');
  const [detail, setDetail] = React.useState(null);   // { it, cat }
  const [recResult, setRecResult] = React.useState(null); // { id, msg }
  const [, setVersion] = React.useState(0);
  const bump = ()=> setVersion(v=>v+1);
  const openItem = (it)=>{ const c = MENU.find(x=>x.items.some(i=>i.id===it.id)); setDetail({ it, cat: c?c.cat:'' }); };
  const cats = ['All', ...MENU.map(c=>c.cat)];
  const totalItems = MENU.reduce((s,c)=>s+c.items.length,0);
  const noPhoto = MENU.reduce((s,c)=>s+c.items.filter(i=>!i.photo).length,0);
  const off = MENU.reduce((s,c)=>s+c.items.filter(i=>!i.avail).length,0);
  const shown = cat==='All' ? MENU : MENU.filter(c=>c.cat===cat);

  return (
    <div>
      <PageHead eyebrow="Menu Manager" title="Your Lasso menu"
        sub={`${totalItems} items across ${MENU.length} categories · last synced 4 min ago`}
        right={<div style={{ display:'flex', gap:10, alignItems:'center' }}>
          <Segmented options={[{value:'items',label:'Items'},{value:'estate',label:'By estate'}]} value={view} onChange={setView}/>
          {view==='items' && <><Btn kind="white" icon={<I.refresh c="var(--fg-primary)" s={15}/>}>Sync</Btn><Btn kind="primary" icon={<I.plus c="var(--dust-cream)" s={16}/>} onClick={()=>setAdding(true)}>Add item</Btn></>}
        </div>}/>

      {view==='estate' ? <EstateRankingView app={app}/> : (
      <>

      {/* health score band */}
      <Card pad={0} style={{ overflow:'hidden', marginBottom:16 }}>
        <div style={{ display:'flex' }}>
          <div style={{ width:240, flexShrink:0, padding:'20px 22px', borderRight:'1px solid var(--soft-line)', display:'flex', alignItems:'center', gap:16 }}>
            <Ring pct={78} size={84} stroke={9} color="var(--brand-orange)">
              <div style={{ textAlign:'center' }}>
                <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:24, color:'var(--fg-primary)', lineHeight:1 }}>78</div>
                <div style={{ fontFamily:'var(--font-body)', fontSize:9, color:'var(--warm-stone)' }}>of 100</div>
              </div>
            </Ring>
            <div>
              <Eyebrow style={{ marginBottom:5 }}>Menu health</Eyebrow>
              <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:17, color:'var(--fg-primary)' }}>Good</div>
              <div style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)', marginTop:3, lineHeight:1.4 }}>{noPhoto} items need photos · {off} switched off</div>
            </div>
          </div>
          <div style={{ flex:1, padding:'15px 20px', overflowX:'auto' }}>
            <Eyebrow style={{ marginBottom:11 }}><I.sparkle c="var(--brand-orange)" s={12} f/> &nbsp;Recommendations to raise your score</Eyebrow>
            <div data-score-recommendations="" data-menu-recommendations="" style={{ display:'flex', gap:11 }}>
              {MENU_RECS.map(r=>{
                const Icon = I[r.icon] || I.info;
                const ACT = {
                  r1:{ hook:'add-photos',   run:()=>{ const it = allMenuItems().find(x=>!x.photo && !x.photoUrl); openItem(it); setRecResult({ id:r.id, msg:`Opened “${it.name}” — use Edit image to pick or upload from your asset library.` }); } },
                  r2:{ hook:'promote',      run:()=>{ const it = allMenuItems().find(x=>x.id==='m2'); app.openBuilder('bletchley', it); setRecResult({ id:r.id, msg:'Campaign builder opened with Pepperoni Storm targeted at Bletchley.' }); } },
                  r3:{ hook:'review',       run:()=>{ const it = allMenuItems().find(x=>!x.avail); openItem(it); setRecResult({ id:r.id, msg:`Opened “${it.name}” — re-enable it or keep it off deliberately.` }); } },
                  r4:{ hook:'build-bundle', run:()=>{ setRecResult({ id:r.id, msg:'Bundles can’t save yet — no bundle table/contract exists. Documented as a missing contract; nothing faked.' }); } },
                  r5:{ hook:'launch',       run:()=>{ const it = allMenuItems().find(x=>x.id==='m8'); app.openBuilder(null, it); setRecResult({ id:r.id, msg:'Campaign builder opened with Dirty Loaded Fries as the hero item.' }); } },
                }[r.id];
                return (
                  <div key={r.id} title={r.detail} style={{ width:188, flexShrink:0, background:'var(--bg-app)', border:'1px solid var(--soft-line)', borderRadius:12, padding:'12px 13px', display:'flex', flexDirection:'column', gap:8 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <div style={{ width:28, height:28, borderRadius:8, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon c="var(--brand-orange)" s={15}/></div>
                      <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:12, color:'var(--fg-primary)', lineHeight:1.2 }}>{r.text}</span>
                    </div>
                    <p style={{ margin:0, fontFamily:'var(--font-body)', fontSize:10.5, color:'var(--warm-stone)', lineHeight:1.4, flex:1 }}>{r.detail}</p>
                    {recResult && recResult.id===r.id && (
                      <div data-recommendation-result="" style={{ fontFamily:'var(--font-body)', fontSize:10, lineHeight:1.45, color: r.id==='r4'?'#a86d12':'#247a41', background: r.id==='r4'?'rgba(224,153,42,0.1)':'rgba(46,139,78,0.08)', border:'1px solid', borderColor: r.id==='r4'?'rgba(224,153,42,0.3)':'rgba(46,139,78,0.25)', borderRadius:8, padding:'6px 8px', animation:'v-pop 200ms var(--ease-out)' }}>{recResult.msg}</div>
                    )}
                    <button data-action={ACT.hook} data-recommendation-action={ACT.hook} onClick={ACT.run}
                      style={{ alignSelf:'flex-start', fontFamily:'var(--font-display)', fontWeight:800, fontSize:11.5, color:'var(--brand-orange)', background:'none', border:'none', cursor:'pointer', padding:0, display:'inline-flex', alignItems:'center', gap:4 }}>
                      {r.action} <I.arrow c="var(--brand-orange)" s={13}/>
                    </button>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </Card>

      {/* category filter */}
      <div style={{ display:'flex', gap:8, marginBottom:13, flexWrap:'wrap' }}>
        {cats.map(c=>{
          const on = c===cat;
          return <button key={c} onClick={()=>setCat(c)} style={{ padding:'7px 13px', borderRadius:10, cursor:'pointer',
            background: on?'var(--dark-chocolate)':'var(--bg-surface)', color: on?'var(--dust-cream)':'var(--fg-primary)',
            border:'1px solid', borderColor: on?'var(--dark-chocolate)':'var(--soft-line)',
            fontFamily:'var(--font-display)', fontWeight:700, fontSize:12.5 }}>{c}</button>;
        })}
      </div>

      {/* table */}
      <Card pad={0} style={{ overflow:'hidden' }}>
        <div style={{ display:'grid', gridTemplateColumns:'2.4fr 0.8fr 1fr 1.3fr 0.9fr 1fr 1fr 1.1fr', gap:10, padding:'11px 18px', borderBottom:'1px solid var(--soft-line)', background:'var(--bg-app)' }}>
          {['Item','Price','Availability','Popularity','Margin','Photo','Modifiers','Trend'].map((h,i)=>(
            <span key={h} style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--warm-stone)', textAlign: i===7?'right':'left' }}>{h}</span>
          ))}
        </div>
        {shown.map(c=>(
          <div key={c.cat}>
            <div style={{ padding:'9px 18px', background:'var(--bg-elevated)', borderBottom:'1px solid var(--soft-line)', display:'flex', alignItems:'center', gap:9 }}>
              <span style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:12.5, color:'var(--fg-primary)', letterSpacing:'0.02em' }}>{c.cat}</span>
              <span style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>{c.items.length} items</span>
            </div>
            {c.items.map((it,i)=> <MenuRow key={it.id} it={it} app={app} onOpen={openItem} last={i===c.items.length-1}/>)}
          </div>
        ))}
      </Card>
      </>
      )}

      {adding && <AddItemModal app={app} onClose={()=>setAdding(false)} onAdd={(item,catName)=>{
        let c = MENU.find(x=>x.cat===catName);
        if(!c){ c={ cat:catName, items:[] }; MENU.push(c); }
        c.items.push(item);
        bump();
        setAdding(false);
        setCat(catName);
        app.toast(`“${item.name}” added to ${catName}`);
      }}/>}

      {detail && <ItemInsightDrawer app={app} it={detail.it} cat={detail.cat} onClose={()=>setDetail(null)} onSave={bump}/>}
    </div>
  );
}

Object.assign(window, { MenuScreen });
