/* ============================================================
   app.jsx — shell: sidebar, topbar, bento layout, mount
   ============================================================ */

function useTheme() {
  const [theme, setTheme] = useLocalState("theme", "light");
  useEffect(() => { document.documentElement.setAttribute("data-theme", theme); }, [theme]);
  return [theme, setTheme];
}

function Sidebar({ active, onNav, onSettings }) {
  const items = [
    { id: "top", icon: "home", label: "Overzicht" },
    { id: "finance", icon: "wallet", label: "Financiën" },
    { id: "agenda", icon: "calendar", label: "Agenda" },
    { id: "habits", icon: "checkCircle", label: "Gewoontes" },
    { id: "goals", icon: "target", label: "Doelen" },
  ];
  return (
    <aside className="sidebar">
      <div className="sb-logo">{(window.__roanName || "R").slice(0,1).toUpperCase()}</div>
      {items.map(it => (
        <button key={it.id} className={"sb-item" + (active === it.id ? " active" : "")} onClick={() => onNav(it.id)}>
          <Icon name={it.icon} />
          <span className="sb-tip">{it.label}</span>
        </button>
      ))}
      <div className="sb-spacer" />
      <button className="sb-item" onClick={onSettings}><Icon name="settings" /><span className="sb-tip">Instellingen</span></button>
    </aside>
  );
}

function Topbar({ theme, setTheme, name, onSettings }) {
  const now = new Date();
  const initial = (name || "R").slice(0, 1).toUpperCase();
  return (
    <div className="topbar">
      <div>
        <div className="greet-eyebrow" style={{ textTransform: "capitalize" }}>{fmtDateNL(now)}</div>
        <h1 className="greet-title">{greetingNL(now)}, {name || "Roan"}</h1>
      </div>
      <div className="topbar-right">
        <span className="pill"><Icon name="search" /> Zoeken</span>
        <button className="icon-btn" title="Meldingen"><Icon name="bell" /></button>
        <button className="icon-btn" onClick={() => setTheme(theme === "light" ? "dark" : "light")} title="Thema wisselen">
          <Icon name={theme === "light" ? "moon" : "sun"} />
        </button>
        <button className="avatar" onClick={onSettings} title="Instellingen" style={{ border: "none", cursor: "pointer" }}>{initial}</button>
      </div>
    </div>
  );
}

function App() {
  const [theme, setTheme] = useTheme();
  const [active, setActive] = useState("top");
  const [settings, setSettings] = useLocalState("settings", { name: "Roan", accent: "coral", waterGoal: 8, sportGoal: 250 });
  const [settingsOpen, setSettingsOpen] = useState(false);
  useEffect(() => { applyAccent(settings.accent); }, [settings.accent]);
  useEffect(() => { window.__roanName = settings.name; }, [settings.name]);
  const refs = {
    top: useRef(null), finance: useRef(null), agenda: useRef(null),
    habits: useRef(null), goals: useRef(null),
  };
  const nav = (id) => {
    setActive(id);
    const el = refs[id] && refs[id].current;
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 18;
      window.scrollTo({ top: id === "top" ? 0 : y, behavior: "smooth" });
    }
  };

  return (
    <div className="app">
      <Sidebar active={active} onNav={nav} onSettings={() => setSettingsOpen(true)} />
      <main className="main">
        <div className="main-inner" ref={refs.top}>
          <Topbar theme={theme} setTheme={setTheme} name={settings.name} onSettings={() => setSettingsOpen(true)} />
          <div className="bento">
            {/* Row 1 — finance */}
            <div className="col-7" ref={refs.finance} style={{ display: "flex" }}><NetWorthWidget /></div>
            <div className="col-5" style={{ display: "flex" }}><BudgetWidget /></div>

            {/* Row 2 — wellbeing */}
            <div className="col-4" style={{ display: "flex" }}><AccountsWidget /></div>
            <div className="col-4" ref={refs.habits} style={{ display: "flex" }}><HabitsWidget /></div>
            <div className="col-4" style={{ display: "flex" }}><MoodWidget /></div>

            {/* Row 3 — agenda */}
            <div className="col-8" ref={refs.agenda} style={{ display: "flex" }}><CalendarWidget /></div>
            <div className="col-4" style={{ display: "flex" }}><TodoWidget /></div>

            {/* Row 4 — planning */}
            <div className="col-5" ref={refs.goals} style={{ display: "flex" }}><GoalsWidget /></div>
            <div className="col-3" style={{ display: "flex" }}><GratitudeWidget /></div>
            <div className="col-4" style={{ display: "flex" }}><BalanceWheelWidget /></div>

            {/* Row 5 — lezen + energie + slaap */}
            <div className="col-4" style={{ display: "flex" }}><ReadingWidget /></div>
            <div className="col-4" style={{ display: "flex" }}><EnergieWidget /></div>
            <div className="col-4" style={{ display: "flex" }}><SlaapWidget /></div>

            {/* Row 6 — lichaam + tijdsbesteding + identiteit */}
            <div className="col-4" style={{ display: "flex" }}><LichaamWidget /></div>
            <div className="col-4" style={{ display: "flex" }}><TijdsbestedingWidget /></div>
            <div className="col-4" style={{ display: "flex" }}><IdentiteitWidget /></div>
          </div>
          <div style={{ textAlign: "center", marginTop: 30, fontSize: 12, color: "var(--text-3)", fontWeight: 600 }}>
            Alles wordt lokaal in je browser bewaard · {NL_MONTHS[new Date().getMonth()]} {new Date().getFullYear()}
          </div>
        </div>
      </main>
      <SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)}
        settings={settings} setSettings={setSettings} theme={theme} setTheme={setTheme} />
    </div>
  );
}

// make every direct grid child fill its cell
const _styleFix = document.createElement("style");
_styleFix.textContent = ".bento > div > .card { flex: 1; width: 100%; }";
document.head.appendChild(_styleFix);

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