/* NutriDMS — Registered Customer Dashboard (screens/customer-dashboard.jsx)
   Home (points/nutrition/last meal), meal history w/ nutrition, receipts,
   quick reorder, rewards, offers, favorites. Reads window.CustomerEngagement.
   Exports window.CustomerDashboard (page === "customer-dashboard"). */
(function () {
  const { useState: dS } = React;
  const CE = () => window.CustomerEngagement;
  const I = (n, s, st) => <Icon name={n} size={s || 16} stroke={st || 2} />;
  const money = (n) => "$" + (Math.round((n || 0) * 100) / 100).toFixed(2);
  const when = (t) => { const days = Math.floor((Date.now() - t) / 864e5); if (days === 0) return "Today"; if (days === 1) return "Yesterday"; if (days < 30) return days + "d ago"; return new Date(t).toLocaleDateString(); };

  function CustomerDashboard() {
    const ce = CE();
    const [tab, setTab] = dS("home");
    if (!ce) return <div className="cd-wrap"><div className="cd-phone"><div className="qr-empty">Engagement engine not loaded.</div></div></div>;

    const me = ce.customers().find((c) => c.type === "registered") || ce.customers()[0];
    const orders = ce.orders(me.id);
    const last = orders[0];
    const s = ce.settings();
    const tiers = s.loyalty.tiers.slice().sort((a, b) => a.min - b.min);
    const idx = tiers.reduce((acc, t, i) => (me.points >= t.min ? i : acc), 0);
    const nextTier = tiers[idx + 1];
    const toNext = nextTier ? nextTier.min - me.points : 0;
    const progress = nextTier ? Math.min(100, ((me.points - tiers[idx].min) / (nextTier.min - tiers[idx].min)) * 100) : 100;
    const totalCal = orders.reduce((a, o) => a + (o.calories || 0), 0);
    const favs = Object.entries(orders.reduce((m, o) => { m[o.meal] = (m[o.meal] || 0) + 1; return m; }, {})).sort((a, b) => b[1] - a[1]);
    const offers = ce.promos().filter((p) => p.active);

    const reorder = (meal) => { ce.addOrder({ customerId: me.id, meal: meal, price: (last ? last.price : 14.99), calories: 500, protein: 24, points: 15, channel: "Reorder" }); try { window.__toast && window.__toast("Reordered " + meal); } catch (e) {} };

    const TABS = [["home", "Home", "house"], ["history", "History", "history"], ["rewards", "Rewards", "award"], ["offers", "Offers", "ticket"], ["favorites", "Favorites", "heart"]];

    return (
      <div className="cd-wrap">
        <div className="cd-phone">
          <div className="cd-topbar"><span className="cd-hello">Hello {me.firstName}</span><span className="cd-tier-badge">{me.tier}</span></div>
          <div className="cd-screen">
            {tab === "home" && (
              <div className="cd-home">
                <div className="cd-points-card">
                  <div className="cd-points-top"><span>Points balance</span><b>{me.points.toLocaleString()}</b></div>
                  <div className="cd-prog"><span style={{ width: progress + "%" }} /></div>
                  <div className="cd-points-sub">{nextTier ? (toNext.toLocaleString() + " pts to " + nextTier.name) : "Top tier reached 🎉"}</div>
                </div>
                <div className="cd-stats">
                  <div className="cd-stat"><b>{orders.length}</b><span>Orders</span></div>
                  <div className="cd-stat"><b>{totalCal.toLocaleString()}</b><span>kcal tracked</span></div>
                  <div className="cd-stat"><b>{money(orders.reduce((a, o) => a + o.price, 0))}</b><span>Lifetime</span></div>
                </div>
                {last && (
                  <div className="cd-sec">
                    <div className="cd-sec-h">Last meal</div>
                    <div className="cd-lastmeal">
                      <div><b>{last.meal}</b><span>{last.calories} kcal · {last.protein}g protein · {when(last.at)}</span></div>
                      <button className="cd-mini" onClick={() => reorder(last.meal)}>{I("repeat", 13)} Reorder</button>
                    </div>
                  </div>
                )}
                {(me.allergies || []).length > 0 && <div className="cd-allergy">{I("shield-alert", 13)} Allergy profile: {me.allergies.join(", ")}</div>}
              </div>
            )}
            {tab === "history" && (
              <div className="cd-list">
                <div className="cd-sec-h">Meal history</div>
                {orders.map((o) => (
                  <div key={o.id} className="cd-histrow">
                    <div className="cd-hist-body"><b>{o.meal}</b><span>{o.calories} kcal · {o.protein}g P · {o.channel} · {when(o.at)}</span></div>
                    <div className="cd-hist-right"><span className="cd-hist-price">{money(o.price)}</span><span className="cd-hist-pts">+{o.points} pts</span></div>
                  </div>
                ))}
                {orders.length === 0 && <div className="qr-empty">No orders yet.</div>}
              </div>
            )}
            {tab === "rewards" && (
              <div className="cd-list">
                <div className="cd-sec-h">Your tier & rewards</div>
                <div className="cd-tiers">{tiers.map((t, i) => (
                  <div key={t.name} className={"cd-tiercard" + (i === idx ? " on" : "") + (i <= idx ? " reached" : "")}>
                    <div className="cd-tier-top"><b>{t.name}</b>{i === idx && <span>Current</span>}</div>
                    <span className="cd-tier-min">{t.min.toLocaleString()}+ pts</span>
                    <em>{t.perk}</em>
                  </div>
                ))}</div>
                <div className="cd-reward-note">{I("gift", 13)} Birthday reward: {s.loyalty.birthdayReward} pts · Referral: {s.loyalty.referralReward} pts · Double points {s.loyalty.doublePointDay}</div>
              </div>
            )}
            {tab === "offers" && (
              <div className="cd-list">
                <div className="cd-sec-h">Offers for you</div>
                {offers.map((p) => (
                  <div key={p.id} className="cd-offer"><span className="cd-offer-ic">{I("ticket", 16)}</span><div><b>{p.name}</b><span>{p.type}</span></div></div>
                ))}
                {offers.length === 0 && <div className="qr-empty">No active offers right now.</div>}
                <p className="cd-consent-note">{I("shield-check", 11)} You receive offers on: {(me.consent || []).join(", ") || "no channels — update in settings"}.</p>
              </div>
            )}
            {tab === "favorites" && (
              <div className="cd-list">
                <div className="cd-sec-h">Your favorites</div>
                {favs.map(([meal, n]) => (
                  <div key={meal} className="cd-favrow"><div><b>{meal}</b><span>Ordered {n}×</span></div><button className="cd-mini" onClick={() => reorder(meal)}>{I("repeat", 13)} Reorder</button></div>
                ))}
                {favs.length === 0 && <div className="qr-empty">Order a few meals to build your favorites.</div>}
              </div>
            )}
          </div>
          <div className="cd-tabbar">{TABS.map(([id, l, ic]) => <button key={id} className={"cd-tabbtn" + (tab === id ? " on" : "")} onClick={() => setTab(id)}>{I(ic, 18)}<span>{l}</span></button>)}</div>
        </div>
        <div className="qr-exit"><button onClick={() => { try { (window.__setPage || (() => {}))("customer-crm"); } catch (e) {} }}>{I("x", 16)} Exit preview</button></div>
      </div>
    );
  }
  window.CustomerDashboard = CustomerDashboard;
})();
