/* Dashboard — calorie rings, announcements, weight chart, today's snippet */
const { useState, useMemo } = React;
const { Ring, Eyebrow, MacroBar, Placeholder, Icon, DataRow, LineChart } = window;

function Dashboard({ profile, plan, goToMeals, goToGallery, goToProfile }) {
  // Compute today's consumed (mock — based on what the user has "checked off")
  const [checked, setChecked] = useState({ breakfast: true, snack1: true, lunch: false, snack2: false, dinner: false });
  const consumed = useMemo(() => {
    const ids = Object.entries(plan).filter(([slot]) => checked[slot]).map(([_, id]) => id);
    let kcal = 0, p = 0, c = 0, f = 0;
    ids.forEach(id => {
      const m = window.MOCK.MEAL_LIBRARY.find(x => x.id === id);
      if (m) { kcal += m.kcal; p += m.p; c += m.c; f += m.f; }
    });
    return { kcal, p, c, f };
  }, [checked, plan]);

  const target = profile.target;
  const macros = profile.macros;

  // Weekly budget redistribution narrative
  const weeklyBudget = target * 7;
  const dayN = 4; // mock: it's Thursday
  const consumedSoFar = target * (dayN - 1) - 180; // mock: under by 180 over the week
  const remaining = weeklyBudget - consumedSoFar;
  const remainingDays = 7 - dayN + 1;
  const adjustedTarget = Math.round(remaining / remainingDays);
  const delta = adjustedTarget - target;

  return (
    <div className="col fade-in" style={{ gap: 32 }}>
      {/* Header row */}
      <div className="between" style={{ alignItems: "end" }}>
        <div>
          <Eyebrow>Today • Thursday, March 14</Eyebrow>
          <h1 className="h-hero" style={{ marginTop: 12, fontSize: 56 }}>
            Hey, {profile.nickname || "Juan"}. <span className="muted">Let's eat.</span>
          </h1>
        </div>
        <div className="row" style={{ gap: 10 }}>
          <button className="btn btn-ghost btn-sm"><Icon name="bell" size={14} /> 2 new</button>
          <button className="btn btn-dark btn-sm" onClick={goToMeals}>Today's meals <Icon name="arrow" size={14} /></button>
        </div>
      </div>

      {/* Calorie rings + macros */}
      <div className="grid-2" style={{ gap: 20 }}>
        <div className="card" style={{ display: "flex", gap: 32, padding: 32 }}>
          <Ring value={consumed.kcal} max={target} size={180} stroke={18}>
            <div className="eyebrow">Today</div>
            <div className="mono" style={{ fontSize: 36, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 2 }}>
              {consumed.kcal.toLocaleString()}
            </div>
            <div className="muted mono" style={{ fontSize: 11, marginTop: 2 }}>
              of {target.toLocaleString()} kcal
            </div>
          </Ring>
          <div className="col" style={{ flex: 1, gap: 20, justifyContent: "center" }}>
            <div>
              <Eyebrow>Remaining</Eyebrow>
              <div className="h-data" style={{ fontSize: 48, marginTop: 4 }}>
                {Math.max(0, target - consumed.kcal).toLocaleString()}
                <span className="muted" style={{ fontSize: 16, fontWeight: 400 }}> kcal</span>
              </div>
            </div>
            <MacroBar p={consumed.p} c={consumed.c} f={consumed.f} target={macros} />
          </div>
        </div>

        <div className="card" style={{ padding: 32, background: delta >= 0 ? "var(--accent-soft)" : "var(--bg-soft)" }}>
          <div className="between" style={{ marginBottom: 12 }}>
            <Eyebrow>Weekly budget</Eyebrow>
            <span className="chip mono" style={{ background: "var(--bg)" }}>
              Day {dayN} of 7
            </span>
          </div>
          <div className="h-data" style={{ fontSize: 40 }}>
            {adjustedTarget.toLocaleString()}
            <span className="muted" style={{ fontSize: 16, fontWeight: 400 }}> kcal today</span>
          </div>
          <p style={{ fontSize: 14, color: "var(--accent-ink)", marginTop: 16, lineHeight: 1.5 }}>
            <strong>+{delta} kcal added</strong> to today because you ate
            ~180 kcal under budget on Mon–Wed. We'll keep balancing through Sunday so your
            weekly target still lands.
          </p>
          <div className="row" style={{ gap: 10, marginTop: 18 }}>
            <button className="btn btn-ghost btn-sm" style={{ background: "var(--bg)" }}>See breakdown</button>
            <button className="btn btn-ghost btn-sm" style={{ background: "var(--bg)" }}>Disable auto-balance</button>
          </div>
        </div>
      </div>

      {/* Today's plan strip */}
      <div className="card flush">
        <div className="between" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
          <div className="row" style={{ gap: 12 }}>
            <Eyebrow>Today's plan</Eyebrow>
            <span className="muted" style={{ fontSize: 12 }}>Tap a meal to log it</span>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={goToMeals}>Open meal plan <Icon name="arrow" size={14} /></button>
        </div>
        <div className="today-strip">
          {[
            { slot: "breakfast", time: "7:30" },
            { slot: "snack1",    time: "10:00", label: "Snack" },
            { slot: "lunch",     time: "12:30" },
            { slot: "snack2",    time: "15:30", label: "Snack" },
            { slot: "dinner",    time: "19:00" },
          ].map((row, i) => {
            const meal = window.MOCK.MEAL_LIBRARY.find(m => m.id === plan[row.slot]);
            const on = checked[row.slot];
            return (
              <button key={row.slot}
                      className={on ? "on" : ""}
                      onClick={() => setChecked(s => ({ ...s, [row.slot]: !s[row.slot] }))}>
                <div className="between">
                  <span className="mono muted" style={{ fontSize: 11 }}>{row.time}</span>
                  <span className="mono" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-muted)" }}>
                    {row.label || row.slot}
                  </span>
                </div>
                <div className="col grow" style={{ gap: 6, justifyContent: "center", padding: "12px 0" }}>
                  <div className="h-data" style={{ fontSize: 32, lineHeight: 1, letterSpacing: "-0.025em" }}>
                    {meal?.kcal}
                    <span className="muted mono" style={{ fontSize: 11, fontWeight: 400, marginLeft: 4 }}>kcal</span>
                  </div>
                  <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.2 }}>{meal?.name}</div>
                  <div className="mono muted" style={{ fontSize: 11 }}>
                    {meal?.p}P · {meal?.c}C · {meal?.f}F
                  </div>
                </div>
                <div className="row" style={{ marginTop: "auto", gap: 6 }}>
                  <span className="chip" style={{ fontSize: 10, padding: "4px 8px",
                    background: on ? "var(--fg)" : "var(--bg-soft)",
                    color: on ? "var(--bg)" : "var(--fg-muted)" }}>
                    {on ? "✓ Logged" : "Tap to log"}
                  </span>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Weight chart + announcements */}
      <div className="split-2">
        <div className="card">
          <div className="between" style={{ marginBottom: 16 }}>
            <div>
              <Eyebrow>Weight trend</Eyebrow>
              <div className="row" style={{ gap: 12, marginTop: 6, alignItems: "baseline" }}>
                <span className="h-data" style={{ fontSize: 36 }}>78.0<span className="muted" style={{ fontSize: 14 }}> kg</span></span>
                <span className="chip" style={{ background: "var(--accent-soft)", borderColor: "transparent", color: "var(--accent-ink)" }}>
                  −4.4 kg since Jan
                </span>
              </div>
            </div>
            <div className="seg">
              <button className="on">10 wks</button>
              <button>3 mo</button>
              <button>6 mo</button>
              <button>1 yr</button>
            </div>
          </div>
          <LineChart data={window.MOCK.WEIGHT_HISTORY} height={220} />
          <div className="row" style={{ gap: 10, marginTop: 16 }}>
            <button className="btn btn-ghost btn-sm"><Icon name="plus" size={14} /> Log today's weight</button>
            <button className="btn btn-ghost btn-sm" onClick={goToGallery}>
              <Icon name="photo" size={14} /> Add progress photo
            </button>
          </div>
        </div>

        <div className="card flush">
          <div className="between" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
            <Eyebrow>Announcements</Eyebrow>
            <button className="muted mono" style={{ fontSize: 11 }}>View all →</button>
          </div>
          <div className="col" style={{ gap: 0 }}>
            {window.MOCK.ANNOUNCEMENTS.map((a, i) => (
              <div key={a.id} style={{
                padding: "16px 24px",
                borderBottom: i < window.MOCK.ANNOUNCEMENTS.length - 1 ? "1px solid var(--line-soft)" : "none",
              }}>
                <div className="row" style={{ gap: 8, marginBottom: 8 }}>
                  <span className="chip" style={{ fontSize: 10, padding: "2px 8px" }}>{a.tag}</span>
                  <span className="muted mono" style={{ fontSize: 11 }}>{a.date}</span>
                </div>
                <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>{a.title}</div>
                <div className="muted" style={{ fontSize: 13 }}>{a.body}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Quick links */}
      <div className="grid-3">
        <QuickLink icon="meal" label="Meal plan" hint="Day & week view, drag to swap" onClick={goToMeals} />
        <QuickLink icon="photo" label="Progress photos" hint="Date-grouped gallery" onClick={goToGallery} />
        <QuickLink icon="user" label="Profile & membership" hint="Redeem codes, settings" onClick={goToProfile} />
      </div>
    </div>
  );
}

function QuickLink({ icon, label, hint, onClick }) {
  return (
    <button onClick={onClick} className="card" style={{
      textAlign: "left", display: "flex", alignItems: "center", gap: 18,
      cursor: "pointer", transition: "border-color .15s",
    }}
    onMouseEnter={e => e.currentTarget.style.borderColor = "var(--fg)"}
    onMouseLeave={e => e.currentTarget.style.borderColor = "var(--line)"}>
      <div style={{
        width: 48, height: 48, borderRadius: 12,
        background: "var(--bg-soft)", display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <Icon name={icon} size={22} />
      </div>
      <div className="col" style={{ gap: 2, flex: 1 }}>
        <div style={{ fontWeight: 600 }}>{label}</div>
        <div className="muted" style={{ fontSize: 13 }}>{hint}</div>
      </div>
      <Icon name="arrow" size={16} color="var(--fg-muted)" />
    </button>
  );
}

Object.assign(window, { Dashboard });
