// ===== MyEmpInfo — App entry =====

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "teal",
  "density": "comfortable",
  "showBackgroundGlow": true,
  "animationSpeed": "normal"
}/*EDITMODE-END*/;

const ACCENT_PRESETS = {
  teal:    { teal: "#00d4a8", purple: "#7c5cff", pink: "#ff5d8f", yellow: "#ffc94d", blue: "#4ec3ff" },
  ocean:   { teal: "#4ec3ff", purple: "#7c5cff", pink: "#ff5d8f", yellow: "#ffc94d", blue: "#00d4a8" },
  warm:    { teal: "#ff8a4c", purple: "#ff5d8f", pink: "#ffc94d", yellow: "#ff8a4c", blue: "#7c5cff" },
  mono:    { teal: "#9aa3bd", purple: "#cbd0e0", pink: "#e0e5f0", yellow: "#9aa3bd", blue: "#9aa3bd" },
};

const LoadingSplash = () => (
  <div style={{
    minHeight: "100vh", display: "flex", flexDirection: "column",
    alignItems: "center", justifyContent: "center", gap: 18,
  }}>
    <div style={{
      width: 48, height: 48, borderRadius: "50%",
      border: "3px solid rgba(255,255,255,0.1)",
      borderTopColor: "var(--teal)",
      animation: "spin 0.9s linear infinite",
    }} />
    <div style={{ fontSize: 14, color: "var(--text-muted, #9aa3bd)" }}>กำลังโหลดข้อมูล…</div>
    <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
  </div>
);

const ErrorSplash = ({ message, onRetry }) => (
  <div style={{
    minHeight: "100vh", display: "flex", flexDirection: "column",
    alignItems: "center", justifyContent: "center", gap: 14, padding: 24,
  }}>
    <div style={{ fontSize: 18, fontWeight: 600 }}>โหลดข้อมูลไม่สำเร็จ</div>
    <div style={{ fontSize: 13, color: "var(--text-muted, #9aa3bd)", maxWidth: 480, textAlign: "center" }}>
      {message}
    </div>
    <button className="btn btn-primary btn-sm shine" onClick={onRetry}>ลองอีกครั้ง</button>
  </div>
);

const App = () => {
  const [route, setRoute] = React.useState("login"); // login | dashboard | employees
  const [drill, setDrill] = React.useState(null);
  const [profile, setProfile] = React.useState(null);
  const [showAddEmployee, setShowAddEmployee] = React.useState(false);
  const [resigning, setResigning] = React.useState(null);
  const [t, setTweaks] = useTweaks(TWEAK_DEFAULTS);
  const [dataVersion, setDataVersion] = React.useState(0);
  const [dataState, setDataState] = React.useState("loading"); // loading | ready | error
  const [dataError, setDataError] = React.useState(null);

  const reloadData = React.useCallback(async () => {
    try {
      await window.MEI_API.loadAll();
      setDataVersion(v => v + 1);
      setDataState("ready");
    } catch (e) {
      console.error("Failed to load data:", e);
      setDataError(e.message || String(e));
      setDataState("error");
    }
  }, []);

  React.useEffect(() => { reloadData(); }, [reloadData]);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme);
    const palette = ACCENT_PRESETS[t.accent] || ACCENT_PRESETS.teal;
    const root = document.documentElement;
    Object.entries(palette).forEach(([k, v]) => root.style.setProperty(`--${k}`, v));
    document.body.style.setProperty("--bg-glow", t.showBackgroundGlow ? "1" : "0");
    if (!t.showBackgroundGlow) {
      document.body.style.backgroundImage = "none";
    } else {
      document.body.style.backgroundImage = "";
    }
  }, [t.theme, t.accent, t.showBackgroundGlow]);

  const openDrill = (data) => setDrill(data);
  const openProfile = (p) => setProfile(p);
  const onLogin = () => setRoute("dashboard");
  const onLogout = () => setRoute("login");

  return (
    <ToastProvider>
      <div style={{ minHeight: "100vh" }} key={dataVersion}>
        {dataState === "loading" && <LoadingSplash />}
        {dataState === "error" && <ErrorSplash message={dataError} onRetry={reloadData} />}

        {dataState === "ready" && route === "login" && <LoginScreen onLogin={onLogin} />}

        {dataState === "ready" && route === "dashboard" && (
          <Dashboard
            onOpenDrill={openDrill}
            onOpenProfile={openProfile}
            onTabChange={(tab) => setRoute(tab)}
            onAddEmployee={() => setShowAddEmployee(true)}
            onResign={(p) => setResigning(p)}
            onLogout={onLogout}
          />
        )}

        {dataState === "ready" && route === "employees" && (
          <EmployeeListScreen
            onBack={() => setRoute("dashboard")}
            onOpenProfile={openProfile}
            onAddEmployee={() => setShowAddEmployee(true)}
            onResign={(p) => setResigning(p)}
          />
        )}

        {/* Overlays */}
        {drill && (
          <DrilldownModal
            open={true}
            data={drill}
            onClose={() => setDrill(null)}
            onOpenProfile={(p) => { setDrill(null); setProfile(p); }}
          />
        )}

        {profile && (
          <ProfileDrawer
            person={profile}
            onClose={() => setProfile(null)}
            onEdit={() => {}}
            onResign={(p) => { setProfile(null); setResigning(p); }}
            onDataChange={reloadData}
          />
        )}

        <NewEmployeeForm
          open={showAddEmployee}
          onClose={() => setShowAddEmployee(false)}
          onDataChange={reloadData}
        />

        {resigning && (
          <ResignForm
            person={resigning}
            onClose={() => setResigning(null)}
            onDataChange={reloadData}
          />
        )}

        <TweaksPanel>
          <TweakSection label="ธีม">
            <TweakRadio
              label="โหมดสี"
              value={t.theme}
              onChange={(v) => setTweaks({ theme: v })}
              options={[
                { value: "dark",  label: "Dark" },
                { value: "light", label: "Light" },
              ]}
            />
            <TweakSelect
              label="ชุดสี Accent"
              value={t.accent}
              onChange={(v) => setTweaks({ accent: v })}
              options={[
                { value: "teal",  label: "Teal (default)" },
                { value: "ocean", label: "Ocean" },
                { value: "warm",  label: "Warm" },
                { value: "mono",  label: "Mono" },
              ]}
            />
            <TweakToggle
              label="Background glow"
              value={t.showBackgroundGlow}
              onChange={(v) => setTweaks({ showBackgroundGlow: v })}
            />
          </TweakSection>

          <TweakSection label="การแสดงผล">
            <TweakRadio
              label="ความหนาแน่น"
              value={t.density}
              onChange={(v) => setTweaks({ density: v })}
              options={[
                { value: "compact",     label: "Compact" },
                { value: "comfortable", label: "Comfy" },
              ]}
            />
          </TweakSection>

          <TweakSection label="คำสั่งลัด">
            <TweakButton
              label="กลับสู่หน้า Login"
              onClick={() => setRoute("login")}
            />
            <TweakButton
              label="ไปหน้า Dashboard"
              onClick={() => setRoute("dashboard")}
            />
            <TweakButton
              label="ไปหน้ารายชื่อ"
              onClick={() => setRoute("employees")}
            />
          </TweakSection>
        </TweaksPanel>

      </div>
    </ToastProvider>
  );
};

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