// eetplanning.jsx — Weekplan + boodschappenlijst-generator
// Houd 't simpel: 7 dagen × 1 maaltijd, optioneel ingrediënten, één knop
// die alle ingrediënten naar de boodschappenlijst zet.

// Use shared sage tokens
const TB = SAGE;

// Inline a section header so we don't depend on variant-b's scope
function SectionHeader({ eyebrow, title, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8, marginTop: 4 }}>
      <div>
        <div style={{ textTransform: 'uppercase', letterSpacing: '0.13em', fontSize: 11, fontWeight: 600, color: TB.inkFaint }}>{eyebrow}</div>
        {title && <div style={{ fontSize: 16, fontWeight: 500, marginTop: 2 }}>{title}</div>}
      </div>
      {right && <div style={{ fontSize: 12, color: TB.inkFaint }}>{right}</div>}
    </div>
  );
}

function mondayOf(d) {
  const day = d.getDay();
  const diff = (day === 0 ? -6 : 1 - day);
  const m = new Date(d);
  m.setDate(d.getDate() + diff);
  m.setHours(0, 0, 0, 0);
  return m;
}

function isoDate(d) {
  return d.toISOString().slice(0, 10);
}

function ScreenEetplan({ state, set, toast }) {
  const [editingDate, setEditingDate] = React.useState(null);
  const [showPreview, setShowPreview] = React.useState(false);
  const monday = mondayOf(TODAY);
  const days = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(monday);
    d.setDate(monday.getDate() + i);
    return d;
  });

  // Open the edit sheet for a date
  const openEdit = (d) => setEditingDate(isoDate(d));

  // Save a meal
  const saveMeal = (iso, name, ingredients) => {
    set(s => ({
      ...s,
      mealPlan: { ...(s.mealPlan || {}), [iso]: { name: name.trim(), ingredients: ingredients.map(i => i.trim()).filter(Boolean) } },
    }));
    toast?.('Opgeslagen');
    setEditingDate(null);
  };

  // Collect all ingredients in this week
  const weekIngredients = React.useMemo(() => {
    const all = new Map(); // lowercased → originally-cased
    for (const d of days) {
      const meal = state.mealPlan?.[isoDate(d)];
      if (!meal) continue;
      for (const ing of (meal.ingredients || [])) {
        const key = ing.toLowerCase().trim();
        if (key && !all.has(key)) all.set(key, ing.trim());
      }
    }
    // Filter out items already on the grocery list
    const onList = new Set((state.groceries || []).map(g => g.label.toLowerCase().trim()));
    return [...all.values()].filter(ing => !onList.has(ing.toLowerCase().trim()));
  }, [state.mealPlan, state.groceries, days]);

  const editingMeal = editingDate ? (state.mealPlan?.[editingDate] || { name: '', ingredients: [] }) : null;

  return (
    <React.Fragment>
      {/* Week summary */}
      <div className="vb-card" style={{ padding: '14px 16px', marginBottom: 12, background: `linear-gradient(135deg, ${TB.accentSoft}, #F1EFE5)` }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div>
            <div className="vb-cap" style={{ color: TB.inkSoft }}>deze week</div>
            <div style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>
              {days.filter(d => (state.mealPlan?.[isoDate(d)]?.name || '').trim()).length} van 7 gepland
            </div>
          </div>
          {weekIngredients.length > 0 && (
            <button onClick={() => setShowPreview(true)} style={{
              padding: '8px 14px', borderRadius: 99, border: 'none', cursor: 'pointer',
              background: TB.accent, color: '#fff', fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
            }}>
              🛒 {weekIngredients.length} naar boodschappen
            </button>
          )}
        </div>
      </div>

      {/* Day cards */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {days.map(d => {
          const iso = isoDate(d);
          const meal = state.mealPlan?.[iso] || { name: '', ingredients: [] };
          const isToday = isoDate(TODAY) === iso;
          const empty = !meal.name?.trim();
          return (
            <button key={iso} onClick={() => openEdit(d)} style={{
              width: '100%', textAlign: 'left', border: 'none', cursor: 'pointer',
              padding: '14px 16px', borderRadius: 14,
              background: isToday ? TB.accentSoft : TB.card,
              fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 44, textAlign: 'center', flexShrink: 0,
                color: isToday ? TB.accent : TB.inkSoft,
              }}>
                <div style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: 0.1, fontWeight: 700 }}>
                  {DAY_SHORT_NL[d.getDay()]}
                </div>
                <div className="vb-num" style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>{d.getDate()}</div>
              </div>
              <div style={{ flex: 1 }}>
                {empty ? (
                  <div style={{ fontSize: 14, color: TB.inkFaint, fontStyle: 'italic' }}>+ wat eet je deze avond?</div>
                ) : (
                  <React.Fragment>
                    <div style={{ fontSize: 15, fontWeight: 500, color: TB.ink }}>{meal.name}</div>
                    {meal.ingredients?.length > 0 && (
                      <div style={{ fontSize: 11, color: TB.inkFaint, marginTop: 2 }}>
                        {meal.ingredients.slice(0, 4).join(', ')}{meal.ingredients.length > 4 ? ' …' : ''}
                      </div>
                    )}
                  </React.Fragment>
                )}
              </div>
              {isToday && (
                <span style={{
                  fontSize: 9, padding: '3px 8px', borderRadius: 99,
                  background: TB.accent, color: '#fff', fontWeight: 600, letterSpacing: 0.1,
                }}>VANDAAG</span>
              )}
            </button>
          );
        })}
      </div>

      {/* Favorites quick-add */}
      {state.recipes?.length > 0 && (
        <div style={{ marginTop: 18 }}>
          <SectionHeader eyebrow="favorieten" title="" right="tik om snel toe te voegen" />
          <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 4, marginLeft: -18, marginRight: -18, paddingLeft: 18, paddingRight: 18 }}>
            {state.recipes.map(r => (
              <button key={r.id} onClick={() => {
                // Find first empty day this week
                const empty = days.find(d => !state.mealPlan?.[isoDate(d)]?.name?.trim());
                if (!empty) { toast?.('Geen lege dag deze week', 'warn'); return; }
                saveMeal(isoDate(empty), r.name, r.ingredients);
              }} style={{
                flexShrink: 0, padding: '10px 14px', borderRadius: 99, border: `1px solid ${TB.hairline}`,
                background: TB.card, fontSize: 12, color: TB.ink, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500,
              }}>+ {r.name}</button>
            ))}
          </div>
        </div>
      )}

      {/* Edit sheet */}
      {editingDate && (
        <MealEditSheet
          dateISO={editingDate}
          meal={editingMeal}
          recipes={state.recipes || []}
          onClose={() => setEditingDate(null)}
          onSave={(name, ingredients) => saveMeal(editingDate, name, ingredients)}
          onClear={() => saveMeal(editingDate, '', [])}
          onSaveAsFavorite={(name, ingredients) => {
            if (!name.trim()) return;
            set(s => ({
              ...s,
              recipes: [...(s.recipes || []), { id: 'rec' + Date.now(), name: name.trim(), ingredients }],
            }));
            toast?.('In favorieten 💚');
          }}
        />
      )}

      {/* Boodschappen preview */}
      {showPreview && (
        <BoodschappenPreviewSheet
          ingredients={weekIngredients}
          onClose={() => setShowPreview(false)}
          onConfirm={(picked) => {
            set(s => ({
              ...s,
              groceries: [
                ...(s.groceries || []),
                ...picked.map(label => ({ id: 'g' + Date.now() + '-' + label.slice(0, 4), label, done: false, fromMealplan: true })),
              ],
            }));
            toast?.(`${picked.length} op de boodschappen 🛒`);
            setShowPreview(false);
          }}
        />
      )}
    </React.Fragment>
  );
}

// ── Edit sheet ───────────────────────────────────────────────────
function MealEditSheet({ dateISO, meal, recipes, onClose, onSave, onClear, onSaveAsFavorite }) {
  const [name, setName] = React.useState(meal.name || '');
  const [ing, setIng]   = React.useState((meal.ingredients || []).join(', '));
  const date = new Date(dateISO);
  const ingredientsArr = ing.split(/[\n,]/).map(s => s.trim()).filter(Boolean);

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(28,42,36,0.32)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} className="vb-sheet" style={{
        width: '100%', background: TB.bg, borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '14px 18px 28px', maxHeight: '85%', overflow: 'auto',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.18)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 2, background: TB.hairline, margin: '0 auto 16px' }} />
        <div className="vb-cap" style={{ color: TB.accent }}>
          {DAY_NAMES_NL[date.getDay()]} {date.getDate()} {MONTH_NAMES_NL[date.getMonth()].slice(0,3)}
        </div>
        <div className="vb-display" style={{ fontSize: 22, marginTop: 2, marginBottom: 14 }}>Wat eet je?</div>

        <label style={{ fontSize: 12, color: TB.inkSoft, display: 'block', marginBottom: 6 }}>Naam gerecht</label>
        <input value={name} onChange={e=>setName(e.target.value)} placeholder="bv. Pasta pesto" style={{
          width: '100%', padding: '12px 14px', fontSize: 15, border: `1px solid ${TB.hairline}`,
          borderRadius: 12, background: TB.card, outline: 'none', boxSizing: 'border-box',
          fontFamily: 'inherit', color: TB.ink, marginBottom: 12,
        }} autoFocus />

        <label style={{ fontSize: 12, color: TB.inkSoft, display: 'block', marginBottom: 6 }}>
          Ingrediënten <span style={{ color: TB.inkFaint }}>(komma of regel)</span>
        </label>
        <textarea value={ing} onChange={e=>setIng(e.target.value)} rows={4}
          placeholder="pasta, pesto, parmezaan"
          style={{
            width: '100%', padding: '12px 14px', fontSize: 15, border: `1px solid ${TB.hairline}`,
            borderRadius: 12, background: TB.card, outline: 'none', boxSizing: 'border-box',
            fontFamily: 'inherit', color: TB.ink, resize: 'vertical',
          }} />

        {recipes.length > 0 && (
          <div style={{ marginTop: 10 }}>
            <div style={{ fontSize: 12, color: TB.inkSoft, marginBottom: 6 }}>of kies een favoriet</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {recipes.map(r => (
                <button key={r.id} onClick={() => { setName(r.name); setIng((r.ingredients || []).join(', ')); }} style={{
                  padding: '6px 12px', borderRadius: 99, border: `1px solid ${TB.hairline}`,
                  background: TB.card, fontSize: 12, color: TB.ink, cursor: 'pointer', fontFamily: 'inherit',
                }}>{r.name}</button>
              ))}
            </div>
          </div>
        )}

        <button onClick={() => onSave(name, ingredientsArr)} disabled={!name.trim()} style={{
          marginTop: 16, width: '100%', padding: '14px', borderRadius: 14, border: 'none',
          background: !name.trim() ? TB.hairline : TB.accent, color: '#fff', fontSize: 15, fontWeight: 600,
          cursor: !name.trim() ? 'not-allowed' : 'pointer', fontFamily: 'inherit',
        }}>Opslaan</button>

        <div style={{ marginTop: 10, display: 'flex', gap: 6 }}>
          <button onClick={() => onSaveAsFavorite(name, ingredientsArr)} disabled={!name.trim()} style={{
            flex: 1, padding: '10px', borderRadius: 10, border: `1px solid ${TB.hairline}`,
            background: 'transparent', color: TB.ink, fontSize: 12, fontWeight: 600,
            cursor: !name.trim() ? 'not-allowed' : 'pointer', fontFamily: 'inherit',
          }}>♥ Naar favorieten</button>
          {meal.name && (
            <button onClick={onClear} style={{
              flex: 1, padding: '10px', borderRadius: 10, border: 'none',
              background: 'transparent', color: '#C44A3A', fontSize: 12, fontWeight: 600,
              cursor: 'pointer', fontFamily: 'inherit',
            }}>Wis dag</button>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Boodschappen preview sheet ──────────────────────────────────
function BoodschappenPreviewSheet({ ingredients, onClose, onConfirm }) {
  const [picked, setPicked] = React.useState(new Set(ingredients.map(i => i.toLowerCase())));
  const toggle = (ing) => {
    const k = ing.toLowerCase();
    const next = new Set(picked);
    if (next.has(k)) next.delete(k); else next.add(k);
    setPicked(next);
  };
  const confirm = () => {
    const list = ingredients.filter(i => picked.has(i.toLowerCase()));
    onConfirm(list);
  };
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(28,42,36,0.32)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} className="vb-sheet" style={{
        width: '100%', background: TB.bg, borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '14px 18px 28px', maxHeight: '85%', overflow: 'auto',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.18)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 2, background: TB.hairline, margin: '0 auto 16px' }} />
        <div className="vb-cap" style={{ color: TB.accent }}>boodschappen genereren</div>
        <div className="vb-display" style={{ fontSize: 22, marginTop: 2 }}>{ingredients.length} ingrediënten deze week</div>
        <div style={{ fontSize: 12, color: TB.inkSoft, marginTop: 4 }}>Vink uit wat je al hebt.</div>

        <div className="vb-card" style={{ padding: 0, marginTop: 12 }}>
          {ingredients.map((ing, i) => {
            const isOn = picked.has(ing.toLowerCase());
            return (
              <button key={ing + i} onClick={() => toggle(ing)} style={{
                width: '100%', textAlign: 'left', border: 'none', cursor: 'pointer',
                padding: '12px 16px', background: 'transparent',
                borderTop: i === 0 ? 'none' : `1px solid ${TB.hairline}`,
                display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'inherit',
                opacity: isOn ? 1 : 0.45,
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                  border: `1.5px solid ${isOn ? TB.accent : TB.hairline}`,
                  background: isOn ? TB.accent : 'transparent', color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12,
                }}>{isOn ? '✓' : ''}</div>
                <span style={{ fontSize: 14, color: TB.ink, textDecoration: isOn ? 'none' : 'line-through' }}>{ing}</span>
              </button>
            );
          })}
        </div>

        <button onClick={confirm} disabled={picked.size === 0} style={{
          marginTop: 14, width: '100%', padding: '14px', borderRadius: 14, border: 'none',
          background: picked.size === 0 ? TB.hairline : TB.accent, color: '#fff', fontSize: 15, fontWeight: 600,
          cursor: picked.size === 0 ? 'not-allowed' : 'pointer', fontFamily: 'inherit',
        }}>Zet {picked.size} op de boodschappen</button>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenEetplan, mondayOf, isoDate });
