/* FoodsTab — Foods screen: 5 daily Indian-market picks with benefit coverage */
(function () {
  const { useMemo } = React;

  function FoodsTab({ today, todayKey }) {
    const useStored = window.useStored;
    const FoodCard = window.FoodCard;
    const PF = window.PulseFloor;

    const [eaten, setEaten] = useStored("pf.foodsEaten", {});

    // Foods the user has actually checked off >=2 times in the past 7 days
    // (excluding today) — layered onto the deterministic ban list.
    const userExcluded = useMemo(() => {
      const todayDi = PF.dayIndex(today);
      const counts = {};
      for (let d = todayDi - 6; d <= todayDi - 1; d++) {
        const dayMap = eaten[String(d)] || {};
        for (const fid in dayMap) {
          if (dayMap[fid]) counts[fid] = (counts[fid] || 0) + 1;
        }
      }
      return new Set(Object.entries(counts).filter(([, c]) => c >= 2).map(([id]) => id));
    }, [eaten, todayKey]);

    const plate = useMemo(() => PF.dailyPlate(today, userExcluded), [todayKey, userExcluded]);

    const todayEaten = eaten[todayKey] || {};
    const eatenCount = Object.values(todayEaten).filter(Boolean).length;
    const GOAL = 3;
    const goalMet = eatenCount >= GOAL;

    const toggle = (id) => {
      setEaten({
        ...eaten,
        [todayKey]: { ...(eaten[todayKey] || {}), [id]: !todayEaten[id] },
      });
    };

    return (
      <div className="fade-in">
        <div className="section-head">
          <h2>Today's plate</h2>
          <span className="meta">
            {goalMet ? (
              <span style={{color: "var(--accent)", fontWeight: 600, letterSpacing: "-0.005em"}}>✓ Goal met · {eatenCount}/5</span>
            ) : (
              <span>{eatenCount}/{GOAL} toward goal</span>
            )}
          </span>
        </div>

        <div className={`plate-banner ${goalMet ? "goal-met" : ""}`}>
          <div>
            <div className="pb-label">{goalMet ? "Nice work today" : `Eat any ${GOAL} of 5 to hit your goal`}</div>
            <div className="pb-title">{goalMet ? "Plate complete" : "Pick what's in your kitchen"}</div>
          </div>
          <div className="pb-meta">
            Plate #{(PF.dayIndex(today) % 999).toString().padStart(3, "0")}
            <b>{eatenCount}/{GOAL}</b>
          </div>
        </div>

        <div className="goal-dots" aria-label={`${eatenCount} of ${GOAL} eaten`}>
          {Array.from({length: GOAL}).map((_, i) => (
            <div key={i} className={`gd ${i < eatenCount ? "filled" : ""} ${goalMet ? "met" : ""}`}></div>
          ))}
          {eatenCount > GOAL && (
            <div className="gd-bonus">+{eatenCount - GOAL} bonus</div>
          )}
        </div>

        <div className="legend">
          {PF.BENEFITS_ORDER.map((b) => {
            const m = PF.BENEFIT_META[b];
            return (
              <span key={b} className="lg-item" style={{"--c": m.color}}>
                <span className="lg-dot"></span>
                {m.label}
              </span>
            );
          })}
        </div>

        <div style={{display: "grid", gap: 10}}>
          {plate.map((f) => (
            <FoodCard key={f.id} food={f} eaten={!!todayEaten[f.id]} onToggle={() => toggle(f.id)} />
          ))}
        </div>

        <div style={{marginTop: 16, padding: "14px 16px", background: "var(--surface)", border: "1px dashed var(--border-strong)", borderRadius: "var(--radius)", fontSize: 12, color: "var(--text-dim)", lineHeight: 1.6}}>
          <b style={{color: "var(--text)", display:"block", marginBottom: 4}}>Why a rotating plate?</b>
          Each day's 5 are picked from a pool of <b style={{color: "var(--text)"}}>30 Indian-market foods</b>, always covering all five benefits — blood flow, stamina, sperm quantity, sperm quality, firm erection. <b style={{color: "var(--accent)"}}>Eat any {GOAL} of 5</b> to meet the daily goal. Anything beyond is bonus.
          <br /><br />
          Nothing repeats more than twice in a 7-day window. If you've actually eaten the same food twice this week, it gets dropped from the rest of the week's suggestions too.
        </div>
      </div>
    );
  }

  window.FoodsTab = FoodsTab;
})();
