// Tidal — Saúde · admin editors
// AthleteEditDrawer: any admin edits an athlete's training plan + diet from CoachView row.
// MenuEditor: any admin edits the public ship menu (7 days × 5 meals).
// Privacy: admin edits prescribed plans; never sees athlete's weight/mood/journal.

const DAYS = ['Seg','Ter','Qua','Qui','Sex','Sáb','Dom'];
const MEAL_LABELS = {
  cafe:         {pt:'café',         en:'breakfast'},
  lanche_manha: {pt:'lanche manhã', en:'morning snack'},
  almoco:       {pt:'almoço',       en:'lunch'},
  lanche:       {pt:'lanche',       en:'snack'},
  jantar:       {pt:'jantar',       en:'dinner'},
  ceia:         {pt:'ceia',         en:'late'},
  madrugada:    {pt:'madrugada',    en:'overnight'},
};
// Map a meal key to its display name; falls back to the meal's own .nome or the key.
const mealName = (k, meal, lang) => meal?.nome || (MEAL_LABELS[k] ? (lang==='pt'?MEAL_LABELS[k].pt:MEAL_LABELS[k].en) : k);
// Sort meals by start hour parsed from "HH:MM–HH:MM"
const sortByHora = (entries) => [...entries].sort((a,b) => {
  const ha = parseInt((a[1]?.hora||'00:00').split(':')[0],10);
  const hb = parseInt((b[1]?.hora||'00:00').split(':')[0],10);
  return ha - hb;
});

// ─── ATHLETE PLAN EDITOR (drawer) ───
const AthleteEditDrawer = ({athleteId, state, setState, onClose, lang, toast}) => {
  const u = state.users.find(x => x.id === athleteId);
  const existing = state.health.athletePlans?.[athleteId] || {focus:'', plan:[], diet:[], notas:''};
  const [focus, setFocus] = useState(existing.focus);
  const [notas, setNotas] = useState(existing.notas);
  const [week, setWeek] = useState(() => {
    if (existing.plan && existing.plan.length === 7) return existing.plan;
    return DAYS.map(d => ({day:d, focus:'', exercises:[]}));
  });
  const [diet, setDiet] = useState(() => {
    if (existing.diet && existing.diet.length > 0) return existing.diet;
    return [
      {refeicao:'Café',   alimentos:[], kcal:0},
      {refeicao:'Almoço', alimentos:[], kcal:0},
      {refeicao:'Lanche', alimentos:[], kcal:0},
      {refeicao:'Jantar', alimentos:[], kcal:0},
    ];
  });
  const [tab, setTab] = useState('treino');
  const [pickerDay, setPickerDay] = useState(null);

  const totalKcal = diet.reduce((a,d)=>a+(d.kcal||0),0);

  const save = () => {
    setState(s => ({
      ...s,
      health: {
        ...s.health,
        athletePlans: {
          ...(s.health.athletePlans || {}),
          [athleteId]: {focus, plan:week, diet, notas, updated:new Date().toISOString().split('T')[0]}
        }
      }
    }));
    toast.push({icon:'check', title:lang==='pt'?'Ficha salva':'Plan saved', sub:`${u.nome.split(' ')[0]} · ${focus||'sem foco'}`});
    onClose();
  };

  const duplicateLastWeek = () => {
    setWeek(state.health.plan.week.map(d => ({...d, exercises:[...d.exercises]})));
    toast.push({icon:'check', title:lang==='pt'?'Semana duplicada':'Week duplicated'});
  };

  return (
    <Drawer onClose={onClose} width={720}>
      <div style={{padding:'24px 28px',borderBottom:'1px solid var(--line-soft)',display:'flex',alignItems:'center',gap:14}}>
        <Avatar user={u} size="md"/>
        <div style={{flex:1}}>
          <div style={{fontFamily:'var(--fs)',fontSize:24,letterSpacing:'-0.4px'}}>{u.nome}</div>
          <div style={{fontSize:12,color:'var(--muted)',fontFamily:'var(--fm)'}}>{u.funcao}</div>
        </div>
        <button className="btn" onClick={onClose}><Icon n="x" size={14}/></button>
      </div>

      {/* Tabs */}
      <div style={{display:'flex',gap:4,padding:'0 28px',borderBottom:'1px solid var(--line-soft)'}}>
        {[{k:'treino',pt:'treino',en:'training'},{k:'dieta',pt:'dieta',en:'diet'},{k:'notas',pt:'notas',en:'notes'}].map(t => (
          <button key={t.k} onClick={()=>setTab(t.k)} style={{
            background:'none',border:'none',padding:'14px 18px',cursor:'pointer',
            fontFamily:'var(--fs)',fontStyle:'italic',fontSize:16,
            color: tab===t.k?'var(--accent)':'var(--muted)',
            borderBottom: tab===t.k?'2px solid var(--accent)':'2px solid transparent',
            marginBottom:-1
          }}>{lang==='pt'?t.pt:t.en}</button>
        ))}
      </div>

      <div style={{padding:'22px 28px 100px',overflow:'auto',flex:1}}>
        {tab === 'treino' && (
          <>
            <div style={{display:'flex',gap:10,alignItems:'center',marginBottom:18}}>
              <input className="input" value={focus} onChange={e=>setFocus(e.target.value)}
                placeholder={lang==='pt'?'foco do plano (ex: hipertrofia 4×/sem)':'plan focus (e.g. hypertrophy 4×/wk)'}
                style={{flex:1}}/>
              <button className="btn" onClick={duplicateLastWeek} title={lang==='pt'?'Duplicar semana anterior':'Duplicate last week'}>
                <Icon n="download" size={13}/>{lang==='pt'?'Copiar última':'Copy last'}
              </button>
            </div>

            <div style={{display:'grid',gap:10}}>
              {week.map((d,i) => (
                <div key={i} style={{
                  background:'var(--cream)',border:'1px solid var(--line-soft)',borderRadius:14,padding:'14px 16px'
                }}>
                  <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:d.exercises.length>0?10:0}}>
                    <div style={{
                      minWidth:36,padding:'4px 0',borderRadius:8,background:'var(--cream-2)',
                      textAlign:'center',fontFamily:'var(--fm)',fontSize:11,letterSpacing:1,textTransform:'uppercase'
                    }}>{d.day}</div>
                    <input className="input" value={d.focus} onChange={e=>{
                      const v=e.target.value; setWeek(w => w.map((x,j) => j===i?{...x,focus:v}:x));
                    }} placeholder={lang==='pt'?'foco do dia (ou descanso)':'day focus (or rest)'} style={{flex:1,fontSize:13}}/>
                    <button className="btn btn-ghost" onClick={()=>setPickerDay(i)} title={lang==='pt'?'Adicionar exercício':'Add exercise'}>
                      <Icon n="plus" size={13}/>
                    </button>
                  </div>
                  {d.exercises.length > 0 && (
                    <div style={{display:'grid',gap:6,paddingLeft:46}}>
                      {d.exercises.map((ex,j) => (
                        <div key={j} style={{
                          display:'grid',gridTemplateColumns:'1.4fr 60px 70px 70px 30px',gap:8,alignItems:'center',
                          padding:'8px 12px',background:'var(--cream-2)',borderRadius:10,fontSize:12.5
                        }}>
                          <input className="input" value={ex.nome} onChange={e=>{
                            const v=e.target.value; setWeek(w=>w.map((x,k)=>k===i?{...x,exercises:x.exercises.map((y,l)=>l===j?{...y,nome:v}:y)}:x));
                          }} style={{padding:'4px 8px',fontSize:12.5}}/>
                          <input className="input" value={ex.series} onChange={e=>{
                            const v=e.target.value; setWeek(w=>w.map((x,k)=>k===i?{...x,exercises:x.exercises.map((y,l)=>l===j?{...y,series:v}:y)}:x));
                          }} placeholder="séries" style={{padding:'4px 8px',fontSize:12,fontFamily:'var(--fm)'}}/>
                          <input className="input" value={ex.reps} onChange={e=>{
                            const v=e.target.value; setWeek(w=>w.map((x,k)=>k===i?{...x,exercises:x.exercises.map((y,l)=>l===j?{...y,reps:v}:y)}:x));
                          }} placeholder="reps" style={{padding:'4px 8px',fontSize:12,fontFamily:'var(--fm)'}}/>
                          <input className="input" value={ex.carga} onChange={e=>{
                            const v=e.target.value; setWeek(w=>w.map((x,k)=>k===i?{...x,exercises:x.exercises.map((y,l)=>l===j?{...y,carga:v}:y)}:x));
                          }} placeholder="carga" style={{padding:'4px 8px',fontSize:12,fontFamily:'var(--fm)'}}/>
                          <button className="btn btn-ghost" style={{padding:4}} onClick={()=>{
                            setWeek(w=>w.map((x,k)=>k===i?{...x,exercises:x.exercises.filter((_,l)=>l!==j)}:x));
                          }}><Icon n="x" size={12}/></button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>

            {pickerDay !== null && (
              <ExercisePicker
                lib={state.health.exerciseLib || []}
                lang={lang}
                onPick={(ex)=>{
                  setWeek(w=>w.map((x,i)=>i===pickerDay?{...x,exercises:[...x.exercises,{nome:ex.nome,series:3,reps:'10',carga:'-'}]}:x));
                  setPickerDay(null);
                }}
                onClose={()=>setPickerDay(null)}/>
            )}
          </>
        )}

        {tab === 'dieta' && (
          <>
            <div style={{padding:'14px 18px',background:'var(--cream-2)',borderRadius:12,marginBottom:18,fontSize:12.5,color:'var(--muted)',lineHeight:1.5}}>
              {lang==='pt'
                ? 'monte o plano alimentar do dia. o atleta marca o que comeu — isso conta pra adesão. peso, humor e diário continuam invisíveis pra você.'
                : 'build the daily meal plan. the athlete checks what they ate — that counts toward adherence. weight, mood and journal stay invisible to you.'}
            </div>
            <div style={{display:'grid',gap:10}}>
              {diet.map((m,i) => (
                <div key={i} style={{background:'var(--cream)',border:'1px solid var(--line-soft)',borderRadius:14,padding:'14px 18px'}}>
                  <div style={{display:'flex',alignItems:'baseline',gap:10,marginBottom:8}}>
                    <input className="input" value={m.refeicao} onChange={e=>{
                      const v=e.target.value; setDiet(d=>d.map((x,j)=>j===i?{...x,refeicao:v}:x));
                    }} style={{width:120,fontFamily:'var(--fs)',fontStyle:'italic',fontSize:14,color:'var(--accent)'}}/>
                    <input type="number" className="input" value={m.kcal} onChange={e=>{
                      const v=+e.target.value||0; setDiet(d=>d.map((x,j)=>j===i?{...x,kcal:v}:x));
                    }} style={{width:90,fontFamily:'var(--fm)',fontSize:12}} placeholder="kcal"/>
                    <span style={{fontFamily:'var(--fm)',fontSize:11,color:'var(--muted)'}}>kcal</span>
                  </div>
                  <textarea className="input" value={m.alimentos.join('\n')} onChange={e=>{
                    const v=e.target.value.split('\n').filter(Boolean); setDiet(d=>d.map((x,j)=>j===i?{...x,alimentos:v}:x));
                  }} rows={3} placeholder={lang==='pt'?'um alimento por linha':'one food per line'}
                    style={{width:'100%',resize:'vertical',fontFamily:'inherit',fontSize:13}}/>
                </div>
              ))}
              <button className="btn" onClick={()=>setDiet(d=>[...d,{refeicao:lang==='pt'?'Refeição extra':'Extra meal',alimentos:[],kcal:0}])} style={{justifyContent:'center'}}>
                <Icon n="plus" size={13}/>{lang==='pt'?'Adicionar refeição':'Add meal'}
              </button>
              <div style={{padding:'12px 18px',background:'var(--accent-soft)',borderRadius:12,fontFamily:'var(--fm)',fontSize:13,display:'flex',justifyContent:'space-between'}}>
                <span style={{color:'var(--ink-2)'}}>{lang==='pt'?'total do dia':'daily total'}</span>
                <strong style={{color:'var(--accent)'}}>{totalKcal} kcal</strong>
              </div>
            </div>
          </>
        )}

        {tab === 'notas' && (
          <>
            <div style={{padding:'14px 18px',background:'#FDF7EE',border:'1px solid var(--line-soft)',borderRadius:12,marginBottom:18,fontSize:12.5,lineHeight:1.5}}>
              <Icon n="lock" size={13}/> {lang==='pt'?'notas privadas — visíveis apenas para administradores. o atleta não vê.':'private notes — visible to admins only. athlete does not see this.'}
            </div>
            <textarea className="input" value={notas} onChange={e=>setNotas(e.target.value)} rows={10}
              placeholder={lang==='pt'?'observações sobre o atleta, lesões, preferências, contexto…':'notes on the athlete — injuries, preferences, context…'}
              style={{width:'100%',resize:'vertical',fontFamily:'inherit',fontSize:13.5,lineHeight:1.6}}/>
          </>
        )}
      </div>

      {/* Footer actions */}
      <div style={{
        position:'sticky',bottom:0,padding:'14px 28px',background:'var(--cream)',borderTop:'1px solid var(--line-soft)',
        display:'flex',gap:10,alignItems:'center'
      }}>
        <button className="btn" onClick={()=>toast.push({icon:'download',title:lang==='pt'?'PDF gerado':'PDF generated'})}>
          <Icon n="download" size={13}/>{lang==='pt'?'Exportar PDF':'Export PDF'}
        </button>
        <div style={{flex:1}}/>
        <button className="btn" onClick={onClose}>{lang==='pt'?'Cancelar':'Cancel'}</button>
        <button className="btn btn-primary" onClick={save}><Icon n="check" size={13}/>{lang==='pt'?'Salvar ficha':'Save plan'}</button>
      </div>
    </Drawer>
  );
};

// Exercise picker modal
const ExercisePicker = ({lib, lang, onPick, onClose}) => {
  const [q, setQ] = useState('');
  const groups = useMemo(() => {
    const filtered = lib.filter(e => !q || e.nome.toLowerCase().includes(q.toLowerCase()));
    const by = {};
    filtered.forEach(e => { (by[e.grupo] = by[e.grupo] || []).push(e); });
    return by;
  }, [lib, q]);

  return (
    <div style={{
      position:'fixed',inset:0,background:'rgba(31,28,23,0.35)',zIndex:200,
      display:'flex',alignItems:'center',justifyContent:'center',padding:20
    }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        background:'var(--cream)',borderRadius:18,width:520,maxWidth:'100%',maxHeight:'80vh',
        display:'flex',flexDirection:'column',boxShadow:'0 20px 60px rgba(31,28,23,0.25)'
      }}>
        <div style={{padding:'18px 22px',borderBottom:'1px solid var(--line-soft)'}}>
          <div className="t-eyebrow" style={{color:'var(--accent)',marginBottom:8}}>{lang==='pt'?'biblioteca de exercícios':'exercise library'}</div>
          <input className="input" autoFocus value={q} onChange={e=>setQ(e.target.value)}
            placeholder={lang==='pt'?'buscar…':'search…'} style={{width:'100%'}}/>
        </div>
        <div style={{overflow:'auto',padding:'10px 22px 18px',flex:1}}>
          {Object.entries(groups).map(([grupo,items]) => (
            <div key={grupo} style={{marginTop:14}}>
              <div style={{fontFamily:'var(--fm)',fontSize:10.5,letterSpacing:1.4,textTransform:'uppercase',color:'var(--muted)',marginBottom:6}}>{grupo}</div>
              <div style={{display:'grid',gap:4}}>
                {items.map((ex,i) => (
                  <button key={i} onClick={()=>onPick(ex)} style={{
                    background:'var(--cream-2)',border:'1px solid transparent',borderRadius:8,padding:'8px 12px',
                    textAlign:'left',cursor:'pointer',fontSize:13,color:'var(--ink)',
                    transition:'all .12s'
                  }} onMouseEnter={e=>{e.currentTarget.style.background='var(--accent-soft)';e.currentTarget.style.borderColor='var(--accent)';}}
                     onMouseLeave={e=>{e.currentTarget.style.background='var(--cream-2)';e.currentTarget.style.borderColor='transparent';}}>
                    {ex.nome}
                  </button>
                ))}
              </div>
            </div>
          ))}
          {Object.keys(groups).length === 0 && (
            <div className="empty" style={{padding:30,textAlign:'center'}}>{lang==='pt'?'nada encontrado':'nothing found'}</div>
          )}
        </div>
        <div style={{padding:'12px 22px',borderTop:'1px solid var(--line-soft)',display:'flex',justifyContent:'flex-end'}}>
          <button className="btn" onClick={onClose}>{lang==='pt'?'Fechar':'Close'}</button>
        </div>
      </div>
    </div>
  );
};

// Generic right-side drawer
const Drawer = ({onClose, width=600, children}) => (
  <div style={{position:'fixed',inset:0,zIndex:150,display:'flex',justifyContent:'flex-end'}}>
    <div onClick={onClose} style={{flex:1,background:'rgba(31,28,23,0.3)'}}/>
    <div style={{
      width,maxWidth:'100%',background:'var(--cream)',display:'flex',flexDirection:'column',
      boxShadow:'-20px 0 60px rgba(31,28,23,0.18)',animation:'slideIn .25s ease-out'
    }}>{children}</div>
    <style>{`@keyframes slideIn { from { transform: translateX(40px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }`}</style>
  </div>
);

// ─── MENU EDITOR (full-page, opens from MenuView when admin clicks "Edit") ───
const MenuEditor = ({state, setState, onClose, lang, toast}) => {
  const [draft, setDraft] = useState(() => JSON.parse(JSON.stringify(state.menu)));
  const [activeDay, setActiveDay] = useState('hoje');
  const [pickerSlot, setPickerSlot] = useState(null);

  const totalDishes = Object.values(draft.hoje||{}).reduce((a,m)=>a+(m.pratos?.length||0),0)
                    + Object.values(draft.amanha||{}).reduce((a,m)=>a+(m.pratos?.length||0),0);

  const updateMeal = (day, mealKey, fn) => {
    setDraft(d => ({...d, [day]: {...d[day], [mealKey]: fn(d[day]?.[mealKey] || {hora:'',pratos:[]})}}));
  };

  const ensureMeal = (day, mealKey, hora) => {
    if (!draft[day] || !draft[day][mealKey]) {
      updateMeal(day, mealKey, () => ({hora, pratos:[]}));
    }
  };

  const copyFromYesterday = () => {
    setDraft(d => ({...d, [activeDay]: JSON.parse(JSON.stringify(activeDay==='hoje'?d.amanha:d.hoje || {}))}));
    toast.push({icon:'check', title:lang==='pt'?'Cardápio copiado':'Menu copied'});
  };

  const publish = () => {
    setState(s => ({...s, menu: {...draft, publicado:true, atualizado:new Date().toISOString().split('T')[0], atualizadoPor:s.role==='admin'?(s.users.find(u=>u.role==='admin')?.id||'admin'):s.users[0].id}}));
    toast.push({icon:'check', title:lang==='pt'?'Cardápio publicado':'Menu published', sub:lang==='pt'?'visível para toda a tripulação':'visible to all crew'});
    onClose();
  };

  return (
    <div style={{position:'fixed',inset:0,zIndex:150,background:'var(--surface-2)',display:'flex',flexDirection:'column'}}>
      {/* Top bar */}
      <div style={{
        padding:'18px 32px',borderBottom:'1px solid var(--line-soft)',background:'var(--cream)',
        display:'flex',alignItems:'center',gap:14
      }}>
        <button className="btn" onClick={onClose}><Icon n="chev_l" size={14}/>{lang==='pt'?'Voltar':'Back'}</button>
        <div style={{flex:1}}>
          <div className="t-eyebrow" style={{color:'var(--accent)'}}>{lang==='pt'?'editor de cardápio':'menu editor'}</div>
          <div style={{fontFamily:'var(--fs)',fontSize:22,letterSpacing:'-0.4px',marginTop:2}}>
            {lang==='pt'?'cardápio do navio,':'ship menu,'} <em style={{color:'var(--muted-2)'}}>{lang==='pt'?'a semana toda.':'the whole week.'}</em>
          </div>
        </div>
        <button className="btn" onClick={copyFromYesterday} title={lang==='pt'?'Copiar do outro dia':'Copy from other day'}>
          <Icon n="download" size={13}/>{lang==='pt'?'Copiar':'Copy'}
        </button>
        <button className="btn btn-primary" onClick={publish}><Icon n="check" size={14}/>{lang==='pt'?'Publicar':'Publish'}</button>
      </div>

      {/* Day tabs */}
      <div style={{padding:'14px 32px 0',background:'var(--cream)',display:'flex',gap:6,borderBottom:'1px solid var(--line-soft)'}}>
        {[{k:'hoje',pt:'hoje',en:'today'},{k:'amanha',pt:'amanhã',en:'tomorrow'}].map(d => (
          <button key={d.k} onClick={()=>setActiveDay(d.k)} style={{
            background:'none',border:'none',padding:'10px 16px',cursor:'pointer',
            fontFamily:'var(--fs)',fontStyle:'italic',fontSize:16,
            color: activeDay===d.k?'var(--accent)':'var(--muted)',
            borderBottom: activeDay===d.k?'2px solid var(--accent)':'2px solid transparent',
            marginBottom:-1
          }}>{lang==='pt'?d.pt:d.en}</button>
        ))}
      </div>

      <div style={{flex:1,overflow:'auto',padding:'24px 32px'}}>
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))',gap:14}}>
          {sortByHora(Object.entries(draft[activeDay]||{})).map(([k,data]) => {
            const displayName = mealName(k, data, lang);
            return (
              <div key={k} style={{background:'var(--cream)',border:'1px solid var(--line-soft)',borderRadius:18,padding:'18px 20px',position:'relative'}}>
                <button className="btn btn-ghost" style={{position:'absolute',top:8,right:8,padding:4}}
                  title={lang==='pt'?'Remover refeição':'Remove meal'}
                  onClick={()=>{
                    if (!confirm(lang==='pt'?`Remover "${displayName}" deste dia?`:`Remove "${displayName}" from this day?`)) return;
                    setDraft(d => { const c={...d,[activeDay]:{...d[activeDay]}}; delete c[activeDay][k]; return c; });
                  }}><Icon n="x" size={12}/></button>
                <div style={{marginBottom:10}}>
                  <input className="input" value={displayName}
                    onChange={e=>updateMeal(activeDay, k, m => ({...m,nome:e.target.value}))}
                    style={{fontFamily:'var(--fs)',fontSize:22,letterSpacing:'-0.4px',color:'var(--accent)',padding:'4px 8px',border:'1px solid transparent',background:'transparent',width:'calc(100% - 28px)'}}
                    onFocus={e=>{e.target.style.borderColor='var(--line-soft)';e.target.style.background='var(--cream-2)';}}
                    onBlur={e=>{e.target.style.borderColor='transparent';e.target.style.background='transparent';}}/>
                  <input className="input" value={data.hora||''}
                    onChange={e=>updateMeal(activeDay, k, m => ({...m,hora:e.target.value}))}
                    placeholder="HH:MM–HH:MM"
                    style={{width:'100%',fontFamily:'var(--fm)',fontSize:11,padding:'5px 8px',marginTop:4,color:'var(--muted)',letterSpacing:0.4}}/>
                </div>
                <div style={{display:'flex',flexDirection:'column',gap:4,marginBottom:10}}>
                  {(data.pratos||[]).map((p,i) => (
                    <div key={i} style={{
                      display:'flex',alignItems:'center',gap:8,padding:'6px 10px',background:'var(--cream-2)',borderRadius:8,fontSize:13
                    }}>
                      <span style={{flex:1}}>{p}</span>
                      <button className="btn btn-ghost" style={{padding:4}} onClick={()=>{
                        updateMeal(activeDay, k, m => ({...m,pratos:m.pratos.filter((_,j)=>j!==i)}));
                      }}><Icon n="x" size={11}/></button>
                    </div>
                  ))}
                  {(data.pratos||[]).length === 0 && (
                    <div style={{fontSize:12,color:'var(--muted)',fontStyle:'italic',padding:'4px 10px'}}>{lang==='pt'?'sem pratos':'no dishes'}</div>
                  )}
                </div>
                <button className="btn" style={{width:'100%',justifyContent:'center'}}
                  onClick={()=>setPickerSlot({day:activeDay, meal:k})}>
                  <Icon n="plus" size={13}/>{lang==='pt'?'Prato':'Dish'}
                </button>
              </div>
            );
          })}

          {/* Add new meal slot */}
          <button className="btn" style={{
            minHeight:180,border:'1.5px dashed var(--line-soft)',background:'transparent',
            display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:8,
            color:'var(--muted)',borderRadius:18
          }} onClick={()=>{
            const name = prompt(lang==='pt'?'Nome da refeição (ex: "lanche da tarde", "ceia"):':'Meal name (e.g. "afternoon snack", "late"):');
            if (!name || !name.trim()) return;
            const hora = prompt(lang==='pt'?'Horário (ex: 16:00–17:00):':'Time (e.g. 16:00–17:00):', '00:00–00:00') || '';
            const key = name.trim().toLowerCase().replace(/\s+/g,'_').replace(/[^a-z0-9_]/g,'').slice(0,20) + '_' + Date.now().toString(36).slice(-3);
            setDraft(d => ({...d, [activeDay]: {...(d[activeDay]||{}), [key]: {nome:name.trim(), hora, pratos:[]}}}));
          }}>
            <Icon n="plus" size={18}/>
            <span style={{fontFamily:'var(--fs)',fontStyle:'italic',fontSize:15}}>{lang==='pt'?'adicionar refeição':'add meal'}</span>
          </button>
        </div>

        {/* Observation */}
        <div style={{marginTop:18,background:'var(--cream)',border:'1px solid var(--line-soft)',borderRadius:18,padding:'18px 22px'}}>
          <div className="t-eyebrow" style={{color:'var(--accent)',marginBottom:8}}>{lang==='pt'?'observação da semana':'note for the week'}</div>
          <textarea className="input" value={draft.obs||''} onChange={e=>setDraft(d=>({...d,obs:e.target.value}))}
            rows={2} placeholder={lang==='pt'?'avisos sobre alergias, eventos especiais…':'notes on allergies, special events…'}
            style={{width:'100%',resize:'vertical',fontFamily:'inherit',fontSize:13.5,fontStyle:'italic'}}/>
        </div>

        <div style={{marginTop:14,fontSize:11,color:'var(--muted)',fontFamily:'var(--fm)',textAlign:'center'}}>
          {totalDishes} {lang==='pt'?'pratos no rascunho':'dishes in draft'} · {draft.publicado ? (lang==='pt'?'última versão pública':'last public version') : (lang==='pt'?'rascunho não publicado':'draft not published')}
        </div>
      </div>

      {pickerSlot && (
        <DishPicker
          lib={state.health?.dishLib || []}
          slot={pickerSlot}
          lang={lang}
          onPick={(dish)=>{
            updateMeal(pickerSlot.day, pickerSlot.meal, m => ({...m,pratos:[...(m.pratos||[]),dish.nome]}));
            setPickerSlot(null);
          }}
          onCustom={(name)=>{
            if (!name.trim()) return;
            updateMeal(pickerSlot.day, pickerSlot.meal, m => ({...m,pratos:[...(m.pratos||[]),name.trim()]}));
            setPickerSlot(null);
          }}
          onClose={()=>setPickerSlot(null)}/>
      )}
    </div>
  );
};

const DishPicker = ({lib, slot, lang, onPick, onCustom, onClose}) => {
  const [q, setQ] = useState('');
  const tagMatch = (t) => t === slot.meal || (slot.meal==='cafe'&&t==='café') || (slot.meal==='almoco'&&t==='almoço') || (slot.meal==='lanche'&&t==='lanche') || (slot.meal==='jantar'&&t==='jantar') || (slot.meal==='ceia'&&t==='ceia');
  const filtered = useMemo(() => {
    return lib.filter(d => (!q || d.nome.toLowerCase().includes(q.toLowerCase())) && (q || tagMatch(d.tag)));
  }, [lib, q, slot]);

  return (
    <div style={{position:'fixed',inset:0,background:'rgba(31,28,23,0.35)',zIndex:200,display:'flex',alignItems:'center',justifyContent:'center',padding:20}} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{background:'var(--cream)',borderRadius:18,width:480,maxWidth:'100%',maxHeight:'80vh',display:'flex',flexDirection:'column',boxShadow:'0 20px 60px rgba(31,28,23,0.25)'}}>
        <div style={{padding:'18px 22px',borderBottom:'1px solid var(--line-soft)'}}>
          <div className="t-eyebrow" style={{color:'var(--accent)',marginBottom:8}}>{lang==='pt'?'biblioteca de pratos':'dish library'}</div>
          <input className="input" autoFocus value={q} onChange={e=>setQ(e.target.value)}
            placeholder={lang==='pt'?'buscar ou digitar prato novo…':'search or type new dish…'} style={{width:'100%'}}
            onKeyDown={e=>{if(e.key==='Enter' && filtered.length===0 && q.trim()) onCustom(q);}}/>
        </div>
        <div style={{overflow:'auto',padding:'10px 22px 14px',flex:1}}>
          <div style={{display:'grid',gap:4}}>
            {filtered.map((d,i) => (
              <button key={i} onClick={()=>onPick(d)} style={{
                background:'var(--cream-2)',border:'1px solid transparent',borderRadius:8,padding:'10px 14px',
                textAlign:'left',cursor:'pointer',fontSize:13.5,color:'var(--ink)',display:'flex',alignItems:'center',gap:10,
                transition:'all .12s'
              }} onMouseEnter={e=>{e.currentTarget.style.background='var(--accent-soft)';e.currentTarget.style.borderColor='var(--accent)';}}
                 onMouseLeave={e=>{e.currentTarget.style.background='var(--cream-2)';e.currentTarget.style.borderColor='transparent';}}>
                <span style={{flex:1}}>{d.nome}</span>
                <span style={{fontFamily:'var(--fm)',fontSize:10,color:'var(--muted)',letterSpacing:0.5,textTransform:'uppercase'}}>{d.tag}</span>
              </button>
            ))}
          </div>
          {q.trim() && !filtered.some(d=>d.nome.toLowerCase()===q.trim().toLowerCase()) && (
            <button onClick={()=>onCustom(q)} className="btn btn-primary" style={{width:'100%',marginTop:10,justifyContent:'center'}}>
              <Icon n="plus" size={13}/>{lang==='pt'?`Adicionar "${q.trim()}"`:`Add "${q.trim()}"`}
            </button>
          )}
        </div>
        <div style={{padding:'12px 22px',borderTop:'1px solid var(--line-soft)',display:'flex',justifyContent:'flex-end'}}>
          <button className="btn" onClick={onClose}>{lang==='pt'?'Fechar':'Close'}</button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {AthleteEditDrawer, MenuEditor});
