// App shell: AppCtx, Sidebar, Topbar, helpers.
// PRODUCTION-READY: branding clickable, perfil clickable, sin toggle Full/Empty.
(() => {
const { useState, useMemo, useEffect, createContext, useContext, useRef } = React;
const Icon = window.Icon;
const I18N = window.I18N;

const AppCtx = createContext(null);
window.AppCtx = AppCtx;
window.useApp = () => useContext(AppCtx);

window.fmtDateShort = (iso, lang) => {
  const d = new Date(iso);
  const m = lang === "es"
    ? ["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"]
    : ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  return `${d.getDate()} ${m[d.getMonth()]}`;
};

window.greeting = (lang) => {
  const h = new Date().getHours();
  const t = I18N[lang];
  if (h < 12) return t.greeting_morning;
  if (h < 19) return t.greeting_afternoon;
  return t.greeting_evening;
};

const NAV = [
  { id: "today",    icon: "sun",       group: "main" },
  { id: "finance",  icon: "coin",      group: "main" },
  { id: "habits",   icon: "leaf",      group: "health" },
  { id: "goals",    icon: "target",    group: "main" },
  { id: "calendar", icon: "cal",       group: "main" },
  { id: "workouts", icon: "dumbbell",  group: "health" },
  { id: "progress", icon: "star",      group: "meta" },
];

function Sidebar({ view, setView }) {
  const { lang, openProfile } = window.useApp();
  const t = I18N[lang];
  const DATA = window.DATA;
  const groups = [
    { key: "main",   label: t.nav_main },
    { key: "health", label: t.nav_health },
    { key: "meta",   label: t.nav_meta },
  ];

  const topStreak = Math.max(0, ...DATA.habits.map(h => h.streak || 0));
  const hasBroken = DATA.habits.some(h => !window.HabitOps.isDoneToday(h) && (h.streak || 0) < (h.best || 0) - 5);
  let avatarState = (window.Storage.get("user") || {}).avatar || "main";
  if (avatarState === "main") {
    if (hasBroken) avatarState = "low";
    else if (topStreak >= 5) avatarState = "happy";
  }

  const user = DATA.user;

  return (
    <aside className="sidebar">
      <button onClick={() => setView("today")} className="brand"
        style={{ background: "transparent", border: "none", cursor: "pointer", textAlign: "left", padding: 0, width: "100%" }}
        title={lang === "es" ? "Ir a Hoy" : "Go to Today"}
      >
        <span className="brand-mark" aria-label="Vida logo"></span>
        <span className="brand-name">{t.appName}</span>
        <span className="brand-sub">{t.tagline}</span>
      </button>
      <nav className="nav">
        {groups.map(g => (
          <React.Fragment key={g.key}>
            <div className="nav-section">{g.label}</div>
            {NAV.filter(n => n.group === g.key).map(n => (
              <button key={n.id}
                className={"nav-item " + (view === n.id ? "active" : "")}
                onClick={() => setView(n.id)}>
                <Icon name={n.icon} size={16} />
                <span className="label-text">{t[n.id]}</span>
                <span className="dot"></span>
              </button>
            ))}
          </React.Fragment>
        ))}
      </nav>
      <button onClick={openProfile} className="profile"
        style={{ background: "transparent", border: "none", cursor: "pointer", textAlign: "left", padding: "10px 12px", width: "100%", borderRadius: 10 }}
        title={lang === "es" ? "Ver perfil" : "View profile"}
      >
        <div className="avatar-img" style={{ backgroundImage: `url("assets/avatars/${avatarState}.png")` }} aria-label="avatar"/>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 500 }}>{user.name}</div>
          <div className="meta">{lang === "es" ? "ver perfil" : "view profile"}</div>
        </div>
      </button>
    </aside>
  );
}
window.Sidebar = Sidebar;

function Topbar({ view }) {
  const { lang, setLang, theme, setTheme, openOnboarding, openSettings } = window.useApp();
  const t = I18N[lang];
  const DATA = window.DATA;
  const d = new Date();
  const dow = lang === "es"
    ? ["domingo","lunes","martes","miercoles","jueves","viernes","sabado"][d.getDay()]
    : ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][d.getDay()];
  const dateStr = `${dow.toUpperCase()} · ${window.fmtDateShort(d.toISOString(), lang).toUpperCase()} · ${d.getFullYear()}`;

  const kickerMap = {
    today: t.today_kicker, finance: "",
    habits: t.habits_kicker, goals: t.goals_kicker,
    calendar: t.cal_kicker, workouts: t.workouts_kicker,
    progress: t.progress_kicker,
  };

  return (
    <header className="topbar">
      <div>
        <div className="kicker" style={{ marginBottom: 4 }}>
          {view === "today" ? dateStr : t[view]}
        </div>
        <div className="crumbs">
          <div className="here">
            {view === "today"
              ? <>{window.greeting(lang)}<span className="italic" style={{color:"var(--ink-3)"}}>, {DATA.user.name.split(" ")[0]}.</span></>
              : t[view]}
          </div>
        </div>
        {kickerMap[view] && view !== "today" && (
          <div className="meta italic" style={{ marginTop: 4, fontFamily: "var(--font-display)", fontSize: 16, letterSpacing: 0, color: "var(--ink-3)" }}>
            {kickerMap[view]}
          </div>
        )}
      </div>
      <div className="top-actions">
        <button className="icon-btn" onClick={openOnboarding} aria-label="welcome" title={lang === "es" ? "Bienvenida" : "Welcome"}>
          <Icon name="compass" size={15} />
        </button>
        <div className="lang-toggle">
          <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
          <button className={lang === "es" ? "on" : ""} onClick={() => setLang("es")}>ES</button>
        </div>
        <button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="theme" title={lang === "es" ? "Tema" : "Theme"}>
          <Icon name={theme === "dark" ? "sun" : "moon"} size={15} />
        </button>
        <button className="icon-btn" onClick={openSettings} aria-label="settings" title={lang === "es" ? "Ajustes" : "Settings"}>
          <Icon name="settings" size={15} />
        </button>
      </div>
    </header>
  );
}
window.Topbar = Topbar;

window.KPI = function KPI({ label, value, suffix, delta, sparkPath, accent }) {
  return (
    <div className="kpi">
      <div className="label">{label}</div>
      <div className="value">{value}{suffix && <small> {suffix}</small>}</div>
      {delta !== undefined && (
        <div className={"delta " + (delta >= 0 ? "up" : "down")}>
          {delta >= 0 ? "↑" : "↓"} {Math.abs(delta)}% vs last month
        </div>
      )}
      {sparkPath && (
        <svg width="120" height="36" viewBox="0 0 120 36" className="spark">
          <path d={sparkPath} fill="none" stroke={accent || "var(--terracotta)"} strokeWidth="1.5" />
        </svg>
      )}
    </div>
  );
};
})();
