/* ============================================================
   Catered · Recipes screen  (window.CATRecipes)
   Organised by meal type — breakfast / lunch / dinner.
   ============================================================ */
const { useState: useSR } = React;

const CATRecipes = ({ state, api }) => {
  const Ic = window.CATIcons;
  const { Btn, Modal, Segmented } = window.CATComp;
  const CAT = window.CAT;
  const D = window.CATDATA;

  const [url, setUrl] = useSR('');
  const [busy, setBusy] = useSR(false);
  const [status, setStatus] = useSR(null);
  const [filter, setFilter] = useSR('all');
  const [manualOpen, setManualOpen] = useSR(false);
  const [mTitle, setMTitle] = useSR('');
  const [mIngs, setMIngs] = useSR('');
  const [mMeal, setMMeal] = useSR('dinner');

  const order = state.recipeOrder;

  async function onScrape() {
    const u = url.trim();
    if (!u) return;
    setBusy(true); setStatus({ type: 'loading', msg: 'Reading the page…' });
    try {
      const parsed = await CAT.scrapeRecipe(u);
      api.addRecipe(parsed); setUrl('');
      setStatus({ type: 'success', msg: `Added “${parsed.title}” — ${parsed.ingredients.length} ingredients.` });
    } catch (e) { setStatus({ type: 'error', msg: e.message || 'Something went wrong.' }); }
    finally { setBusy(false); }
  }
  function saveManual() {
    if (!mTitle.trim() || !mIngs.trim()) return;
    api.addManual({ title: mTitle.trim(), ingredients: mIngs, meal: mMeal });
    setManualOpen(false); setMTitle(''); setMIngs(''); setMMeal('dinner');
    api.toast('Recipe added.');
  }

  function Card({ id }) {
    const r = state.recipes[id];
    if (!r) return null;
    const domain = CAT.sourceDomainOf(r.source_url) || 'added by hand';
    const n = r.ingredients.length;
    return (
      <article className="cat-recipe gg-enter">
        <div className={`cat-recipe-thumb${r.image_url ? '' : ' placeholder'}`}
          style={r.image_url ? { backgroundImage: `url('${r.image_url}')` } : null}>
          {!r.image_url && <Ic.Fork size={28} />}
        </div>
        <button className="cat-recipe-del" title="Remove recipe"
          onClick={() => { if (confirm('Remove this recipe? It will be cleared from any planned days too.')) api.deleteRecipe(id); }}>
          <Ic.X size={15} />
        </button>
        <div className="cat-recipe-body">
          <h3 className="cat-recipe-title">{r.title}</h3>
          <div className="cat-recipe-meta">
            <span className="cat-recipe-domain">{domain}</span>
            <span className="cat-dot" />
            <span>{n} ingredient{n === 1 ? '' : 's'}</span>
          </div>
          <div className="cat-recipe-foot">
            <label className="cat-meal-select">
              <select value={r.meal || 'dinner'} onChange={(e) => api.setRecipeMeal(id, e.target.value)} aria-label="Meal type">
                {D.MEALS.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
              </select>
            </label>
            {r.source_url ? (
              <a className="cat-recipe-link" href={r.source_url} target="_blank" rel="noopener noreferrer">View <Ic.External size={13} /></a>
            ) : null}
          </div>
        </div>
      </article>
    );
  }

  const filters = [{ id: 'all', label: 'All' }, ...D.MEALS.map((m) => ({ id: m.id, label: m.label }))];

  return (
    <div className="gg-container cat-page">
      <header className="cat-head">
        <div className="cat-head-text">
          <window.CATComp.Eyebrow>Recipes</window.CATComp.Eyebrow>
          <h1 className="gg-display cat-title">Your recipe box.</h1>
          <p className="cat-sub">Paste any recipe link and we'll pull the ingredients out for you. Sort each one by meal, then drop it onto the week.</p>
        </div>
      </header>

      <div className="cat-scrape">
        <div className="cat-scrape-row">
          <div className="cat-input-wrap">
            <Ic.Link size={18} />
            <input className="cat-input" type="url" value={url} placeholder="Paste a recipe URL…"
              onChange={(e) => setUrl(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') onScrape(); }}
              autoComplete="off" spellCheck="false" />
          </div>
          <Btn variant="pop" onClick={onScrape} disabled={busy} leftIcon={busy ? null : <Ic.Plus size={17} />}>
            {busy ? 'Reading…' : 'Add recipe'}
          </Btn>
        </div>
        {status && (
          <div className={`cat-status ${status.type}`}>
            {status.type === 'loading' && <span className="cat-spinner" />}
            {status.type === 'success' && <Ic.Check size={15} />}
            {status.type === 'error' && <Ic.X size={15} />}
            <span>{status.msg}</span>
          </div>
        )}
        <button className="cat-link-btn" onClick={() => setManualOpen(true)}><Ic.Pencil size={14} /> Or add one by hand</button>
      </div>

      {order.length === 0 ? (
        <div className="cat-empty">
          <div className="cat-empty-glyph"><Ic.Fork size={26} /></div>
          <div className="cat-empty-title">No recipes yet</div>
          <div className="cat-empty-body">Paste a recipe URL above and we'll do the rest — or add one by hand.</div>
        </div>
      ) : (
        <>
          <div className="cat-filters">
            {filters.map((f) => (
              <button key={f.id} className={`gg-fchip${filter === f.id ? ' sel' : ''}`} onClick={() => setFilter(f.id)}>
                {f.label}
                <span className="cat-filter-count">{f.id === 'all' ? order.length : order.filter((id) => (state.recipes[id].meal || 'dinner') === f.id).length}</span>
              </button>
            ))}
          </div>

          {filter === 'all' ? (
            D.MEALS.map((m) => {
              const ids = order.filter((id) => (state.recipes[id].meal || 'dinner') === m.id);
              if (!ids.length) return null;
              return (
                <section className="cat-recipe-section" key={m.id}>
                  <div className="cat-recipe-grouphead">
                    <span className={`cat-meal-tag t-${m.tint}`}>{m.label}</span>
                    <span className="cat-recipe-groupline" />
                    <span className="cat-recipe-groupcount">{ids.length}</span>
                  </div>
                  <div className="cat-recipe-grid">{ids.map((id) => <Card id={id} key={id} />)}</div>
                </section>
              );
            })
          ) : (
            <div className="cat-recipe-grid">
              {order.filter((id) => (state.recipes[id].meal || 'dinner') === filter).map((id) => <Card id={id} key={id} />)}
            </div>
          )}
        </>
      )}

      <Modal open={manualOpen} onClose={() => setManualOpen(false)} title="Add a recipe by hand"
        subtitle="One ingredient per line — e.g. “2 cloves garlic”.">
        <div className="cat-field">
          <label>Recipe name</label>
          <input className="cat-tinput" value={mTitle} onChange={(e) => setMTitle(e.target.value)} placeholder="e.g. Weeknight lemon pasta" autoFocus />
        </div>
        <div className="cat-field">
          <label>Meal</label>
          <Segmented value={mMeal} onChange={setMMeal} options={D.MEALS.map((m) => ({ value: m.id, label: m.label }))} />
        </div>
        <div className="cat-field">
          <label>Ingredients</label>
          <textarea className="cat-tinput" rows={6} value={mIngs} onChange={(e) => setMIngs(e.target.value)}
            placeholder={'400g spaghetti\n2 lemons\n50g parmesan\n3 cloves garlic'} />
        </div>
        <div className="cat-modal-actions">
          <Btn variant="ghost" onClick={() => setManualOpen(false)}>Cancel</Btn>
          <Btn variant="pop" onClick={saveManual} disabled={!mTitle.trim() || !mIngs.trim()}>Save recipe</Btn>
        </div>
      </Modal>
    </div>
  );
};

window.CATRecipes = { CATRecipes };
