/* Get Fit by Tito Fit — top-level app + routing + Tweaks panel */

const { useState: uS, useEffect: uE, useMemo: uM } = React;
const { Brand, Eyebrow, Icon, Avatar,
        Landing, Login, Onboarding, Dashboard, MealPlan, Gallery, Profile } = window;

const DEFAULT_TWEAKS = /*EDITMODE-BEGIN*/{
  "accent": "lime",
  "theme": "dark",
  "density": "comfy"
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = uS("landing"); // landing | login | onboarding | dashboard | meals | gallery | profile
  const [user, setUser] = uS(null);
  const [profile, setProfile] = uS(null);
  const [plan, setPlan] = uS({ ...window.MOCK.STARTER_PLAN });
  const [weekPlan, setWeekPlan] = uS(window.MOCK.WEEK_PLAN.map(d => ({ ...d })));
  const [tweaks, setTweak] = window.useTweaks(DEFAULT_TWEAKS);

  // Apply tweaks to root
  uE(() => {
    const r = document.documentElement;
    r.setAttribute("data-theme", tweaks.theme || "light");
    r.setAttribute("data-accent", tweaks.accent || "lime");
    r.style.setProperty("--density", tweaks.density === "compact" ? "0.78" : "1");
  }, [tweaks.theme, tweaks.accent, tweaks.density]);

  // After login: if first-time → onboarding; else dashboard
  function handleLogin(u) {
    setUser(u);
    if (u.isFirstTime) setRoute("onboarding");
    else {
      // Seed a mock profile for returning user
      const tdee = 2654;
      setProfile({
        sex: "male", age: 32, weightKg: 78.4, heightCm: 172,
        activity: "moderate", tdee,
        goal: "lose", level: "moderate", target: 2123,
        macros: window.TDEE.macrosForTarget(2123, 78.4, "lose"),
        nickname: u.nickname,
        daysLeft: 24,
      });
      setRoute("dashboard");
    }
  }

  function handleOnboardingDone(data) {
    setProfile({ ...data, nickname: user?.nickname || "Juan", daysLeft: user?.days || 30 });
    setRoute("dashboard");
  }

  function logout() {
    setUser(null);
    setProfile(null);
    setRoute("landing");
  }

  // Pre-app screens
  if (route === "landing")    return (<><Landing go={setRoute} /><TweaksUI tweaks={tweaks} setTweak={setTweak} /></>);
  if (route === "login")      return (<><Login go={setRoute} onLogin={handleLogin} /><TweaksUI tweaks={tweaks} setTweak={setTweak} /></>);
  if (route === "onboarding") return (<><Onboarding user={user} onDone={handleOnboardingDone} /><TweaksUI tweaks={tweaks} setTweak={setTweak} /></>);

  // App shell screens
  return (
    <div className="app-shell">
      <Sidebar route={route} setRoute={setRoute} profile={profile} onLogout={logout} />
      <div className="main">
        <TopBar profile={profile} />
        {route === "dashboard" && (
          <Dashboard profile={profile} plan={plan}
            goToMeals={() => setRoute("meals")}
            goToGallery={() => setRoute("gallery")}
            goToProfile={() => setRoute("profile")} />
        )}
        {route === "meals" && (
          <MealPlan profile={profile} plan={plan} setPlan={setPlan}
                    weekPlan={weekPlan} setWeekPlan={setWeekPlan} />
        )}
        {route === "gallery" && <Gallery />}
        {route === "profile" && (
          <Profile profile={profile} setProfile={setProfile} onLogout={logout}
                   tweaks={tweaks} setTweak={setTweak} />
        )}
      </div>
      <TweaksUI tweaks={tweaks} setTweak={setTweak} />
    </div>
  );
}

/* ============================================================
   Side nav + top bar
   ============================================================ */
function Sidebar({ route, setRoute, profile, onLogout }) {
  const items = [
    { id: "dashboard", icon: "home",  label: "Home" },
    { id: "meals",     icon: "meal",  label: "Meal plan" },
    { id: "gallery",   icon: "photo", label: "Progress" },
    { id: "profile",   icon: "user",  label: "Profile" },
  ];
  return (
    <aside className="sidebar">
      <div style={{ marginBottom: 24 }}>
        <Brand size="sm" />
      </div>

      <nav className="col" style={{ gap: 2 }}>
        {items.map(it => (
          <div key={it.id}
               className={"nav-item" + (route === it.id ? " active" : "")}
               onClick={() => setRoute(it.id)}>
            <Icon name={it.icon} size={18} />
            <span>{it.label}</span>
            {route === it.id && <Icon name="arrow" size={14} style={{ marginLeft: "auto" }} />}
          </div>
        ))}
      </nav>

      <div style={{ marginTop: "auto" }}>
        <div className="card sunken" style={{ padding: 14 }}>
          <Eyebrow>Membership</Eyebrow>
          <div className="row" style={{ gap: 8, marginTop: 8, alignItems: "baseline" }}>
            <span className="mono" style={{ fontWeight: 700, fontSize: 22 }}>{profile?.daysLeft || 24}</span>
            <span className="muted mono" style={{ fontSize: 11 }}>days left</span>
          </div>
          <button className="btn btn-primary btn-sm full"
                  style={{ marginTop: 12, fontSize: 12 }}
                  onClick={() => setRoute("profile")}>
            Top up
          </button>
        </div>

        <button className="nav-item" onClick={onLogout} style={{ marginTop: 8 }}>
          <Icon name="logout" size={18} /> Log out
        </button>
      </div>
    </aside>
  );
}

function TopBar({ profile }) {
  const initials = (profile?.nickname || "JS").slice(0, 2);
  return (
    <div className="topbar">
      <div className="row" style={{ gap: 12 }}>
        <span className="chip mono dot">All systems good</span>
        <span className="muted mono" style={{ fontSize: 12 }}>Last weigh-in: Sun, Mar 09</span>
      </div>
      <div className="row" style={{ gap: 8 }}>
        <button className="btn btn-ghost btn-icon"><Icon name="bell" size={16} /></button>
        <button className="btn btn-ghost btn-icon"><Icon name="settings" size={16} /></button>
        <Avatar name={initials} />
      </div>
    </div>
  );
}

/* ============================================================
   Tweaks panel
   ============================================================ */
const ACCENT_PRESETS = {
  "#d2ff3a": "lime",
  "#ff7a3a": "orange",
  "#3a8aff": "electric",
  "#ff3aa0": "magenta",
};
const ACCENT_TO_HEX = Object.fromEntries(Object.entries(ACCENT_PRESETS).map(([h, n]) => [n, h]));

function TweaksUI({ tweaks, setTweak }) {
  const T = window.TweaksPanel;
  const Section = window.TweakSection;
  const Color = window.TweakColor;
  const Radio = window.TweakRadio;
  if (!T) return null;
  const currentHex = ACCENT_TO_HEX[tweaks.accent] || "#d2ff3a";
  return (
    <T title="Tweaks">
      <Section label="Accent">
        <Color label="Color" value={currentHex}
          options={Object.keys(ACCENT_PRESETS)}
          onChange={hex => setTweak("accent", ACCENT_PRESETS[hex.toLowerCase()] || "lime")} />
      </Section>
      <Section label="Theme">
        <Radio label="Mode" value={tweaks.theme} onChange={v => setTweak("theme", v)}
          options={["light", "dark"]} />
      </Section>
      <Section label="Density">
        <Radio label="Layout" value={tweaks.density} onChange={v => setTweak("density", v)}
          options={["comfy", "compact"]} />
      </Section>
    </T>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
