/* Tachiara client — main App: auth gate, routing, sidebar, tweaks, notifications. */

const ACCENT_PRESETS = {
  "#0F766E": {
    fg: "#FFFFFF",
    hover: "#115E59",
    active: "#134E4A",
    soft: "#ECFDF5",
    soft2: "#D1FAE5",
    ring: "rgba(15,118,110,0.22)",
  },
  "#EA580C": {
    fg: "#FFFFFF",
    hover: "#C2410C",
    active: "#9A3412",
    soft: "#FFF7ED",
    soft2: "#FFEDD5",
    ring: "rgba(234,88,12,0.22)",
  },
  "#4F46E5": {
    fg: "#FFFFFF",
    hover: "#4338CA",
    active: "#3730A3",
    soft: "#EEF2FF",
    soft2: "#E0E7FF",
    ring: "rgba(79,70,229,0.22)",
  },
  "#E11D48": {
    fg: "#FFFFFF",
    hover: "#BE123C",
    active: "#9F1239",
    soft: "#FFF1F2",
    soft2: "#FFE4E6",
    ring: "rgba(225,29,72,0.22)",
  },
  "#0F172A": {
    fg: "#FFFFFF",
    hover: "#1E293B",
    active: "#020617",
    soft: "#F1F5F9",
    soft2: "#E2E8F0",
    ring: "rgba(15,23,42,0.18)",
  },
};
const ACCENT_OPTIONS = Object.keys(ACCENT_PRESETS);

function applyAccent(hex) {
  const p = ACCENT_PRESETS[hex] || ACCENT_PRESETS["#0F766E"];
  const r = document.documentElement.style;
  r.setProperty("--accent", hex in ACCENT_PRESETS ? hex : "#0F766E");
  r.setProperty("--accent-hover", p.hover);
  r.setProperty("--accent-active", p.active);
  r.setProperty("--accent-soft", p.soft);
  r.setProperty("--accent-soft-2", p.soft2);
  r.setProperty("--accent-ring", p.ring);
  r.setProperty("--accent-fg", p.fg);
}

function applyTheme(theme) {
  // 'auto' falls back to system preference.
  let actual = theme;
  if (theme === "auto") {
    actual = window.matchMedia("(prefers-color-scheme: dark)").matches
      ? "dark"
      : "light";
  }
  document.documentElement.setAttribute("data-theme", actual);
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/ {
  accent: "#0F766E",
  theme: "light",
}; /*EDITMODE-END*/

function App() {
  const [me, setMe] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [route, setRoute] = React.useState({ screen: "rooms" });
  const [showNotifications, setShowNotifications] = React.useState(false);
  const [notifData, setNotifData] = React.useState({
    notifications: [],
    unreadCount: 0,
  });

  const tweaksResult = window.useTweaks
    ? window.useTweaks(TWEAK_DEFAULTS)
    : [TWEAK_DEFAULTS, () => {}];
  const t = tweaksResult[0];
  const setTweak = tweaksResult[1];

  React.useEffect(() => {
    applyAccent(t.accent);
  }, [t.accent]);
  React.useEffect(() => {
    applyTheme(t.theme);
    // If 'auto', re-apply when system flips
    if (t.theme === "auto") {
      const mq = window.matchMedia("(prefers-color-scheme: dark)");
      const handler = () => applyTheme("auto");
      mq.addEventListener("change", handler);
      return () => mq.removeEventListener("change", handler);
    }
  }, [t.theme]);

  // Boot: resolve token if any.
  React.useEffect(() => {
    let mounted = true;
    async function boot() {
      if (!window.api.getToken()) {
        setLoading(false);
        return;
      }
      try {
        const { user } = await window.api.auth.me();
        if (mounted) {
          setMe(user);
          setLoading(false);
        }
      } catch (_err) {
        if (mounted) {
          window.api.setToken(null);
          setMe(null);
          setLoading(false);
        }
      }
    }
    boot();
    const onUnauthorized = () => {
      setMe(null);
    };
    window.addEventListener("qc:unauthorized", onUnauthorized);
    return () => {
      mounted = false;
      window.removeEventListener("qc:unauthorized", onUnauthorized);
    };
  }, []);

  // Deep-link: ?join=CODE auto-joins the room after sign-in.
  React.useEffect(() => {
    if (!me) return;
    const params = new URLSearchParams(location.search);
    const code = params.get("join");
    if (!code) return;
    (async () => {
      try {
        const { room } = await window.api.rooms.joinByCode(code);
        // Clean the URL so refresh doesn't re-trigger.
        const cleaned = new URL(location.href);
        cleaned.searchParams.delete("join");
        history.replaceState(null, "", cleaned.toString());
        setRoute({ screen: "room", roomId: room.id });
      } catch (_err) {
        // Silently ignore — invalid/expired code.
      }
    })();
  }, [me?.id]);

  // Refetch notifications only on initial load + focus + after activity changes.
  // Không poll định kỳ — tránh nhấp nháy.
  React.useEffect(() => {
    if (!me) return;
    let cancelled = false;
    async function tick() {
      try {
        const d = await window.api.users.notifications();
        if (!cancelled) setNotifData(d);
      } catch (_err) {
        /* swallow */
      }
    }
    tick();
    const onFocus = () => tick();
    window.addEventListener("focus", onFocus);
    return () => {
      cancelled = true;
      window.removeEventListener("focus", onFocus);
    };
  }, [me?.id]);

  const signOut = () => {
    window.api.setToken(null);
    setMe(null);
    setRoute({ screen: "rooms" });
  };

  const reloadNotifs = async () => {
    try {
      const d = await window.api.users.notifications();
      setNotifData(d);
    } catch (_e) {}
  };

  if (loading) {
    return (
      <div className="auth-shell">
        <div style={{ color: "var(--wf-fg-muted)" }}>
          Đang kiểm tra phiên...
        </div>
      </div>
    );
  }
  if (!me) {
    return <AuthScreen onSignedIn={(user) => setMe(user)} />;
  }

  const navigate = (r) => {
    setRoute(r);
    window.scrollTo(0, 0);
  };
  const unreadCount = notifData.unreadCount || 0;

  return (
    <div className="app-shell">
      <aside className="sidebar">
        <div className="brand">
          <div className="brand-mark">T</div>
          <span>Tachiara</span>
        </div>

        <div className="sidebar-section-title">Chính</div>
        <button
          className={
            "nav-item" +
            (route.screen === "rooms" || route.screen === "room"
              ? " active"
              : "")
          }
          onClick={() => navigate({ screen: "rooms" })}
        >
          <span className="icon">
            <I.users />
          </span>{" "}
          Phòng
        </button>
        <button
          className={"nav-item" + (route.screen === "stats" ? " active" : "")}
          onClick={() => navigate({ screen: "stats" })}
        >
          <span className="icon">
            <I.chart />
          </span>{" "}
          Thống kê
        </button>
        <button
          className={"nav-item" + (route.screen === "profile" ? " active" : "")}
          onClick={() => navigate({ screen: "profile" })}
        >
          <span className="icon">
            <I.user />
          </span>{" "}
          Cá nhân
        </button>

        <div className="sidebar-section-title">Khác</div>
        <button className="nav-item" onClick={() => setShowNotifications(true)}>
          <span className="icon">
            <I.bell />
          </span>
          Thông báo
          {unreadCount > 0 && (
            <span className="badge badge-accent nav-badge">{unreadCount}</span>
          )}
        </button>

        <div className="sidebar-footer">
          <Avatar user={me} />
          <div className="user-info" style={{ flex: 1, minWidth: 0 }}>
            <div
              className="name"
              style={{
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {me.name}
            </div>
            <div
              className="meta"
              style={{
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {me.email}
            </div>
          </div>
          <button
            className="btn btn-ghost btn-icon btn-sm"
            title="Đăng xuất"
            onClick={signOut}
          >
            <span className="icon icon-sm">
              <I.logout />
            </span>
          </button>
        </div>
      </aside>

      <main className="main">
        {route.screen === "rooms" && (
          <RoomsScreen me={me} navigate={navigate} />
        )}
        {route.screen === "room" && (
          <RoomScreen
            me={me}
            navigate={navigate}
            roomId={route.roomId}
            onActivityChange={reloadNotifs}
          />
        )}
        {route.screen === "stats" && (
          <StatsScreen me={me} navigate={navigate} />
        )}
        {route.screen === "profile" && (
          <ProfileScreen me={me} onUserChange={setMe} onSignOut={signOut} />
        )}
      </main>

      <NotificationsDrawer
        open={showNotifications}
        onClose={() => setShowNotifications(false)}
        notifications={notifData.notifications}
        navigate={(r) => {
          setShowNotifications(false);
          navigate(r);
        }}
        onMarkAllRead={async () => {
          await window.api.users.markAllRead();
          reloadNotifs();
        }}
      />

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection label="Giao diện">
            <window.TweakColor
              label="Màu nhấn"
              value={t.accent}
              options={ACCENT_OPTIONS}
              onChange={(v) => setTweak("accent", v)}
            />
            <window.TweakSelect
              label="Theme"
              value={t.theme}
              options={[
                { value: "light", label: "Sáng" },
                { value: "dark", label: "Tối" },
                { value: "auto", label: "Theo hệ thống" },
              ]}
              onChange={(v) => setTweak("theme", v)}
            />
          </window.TweakSection>
          <window.TweakSection label="API">
            <window.TweakButton
              label="Đổi base URL"
              onClick={() => {
                const v = prompt("API base URL", window.api.getBaseURL());
                if (v && v.trim()) window.api.setBaseURL(v.trim());
              }}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

function NotificationsDrawer({
  open,
  onClose,
  notifications,
  navigate,
  onMarkAllRead,
}) {
  const unread = notifications.filter((n) => n.unread).length;
  return (
    <Modal
      open={open}
      onClose={onClose}
      title={`Thông báo${unread > 0 ? ` (${unread})` : ""}`}
      footer={
        <>
          {unread > 0 && (
            <Button variant="ghost" onClick={onMarkAllRead}>
              Đánh dấu đã đọc tất cả
            </Button>
          )}
          <Button variant="secondary" onClick={onClose}>
            Đóng
          </Button>
        </>
      }
    >
      {notifications.length === 0 ? (
        <Empty icon={<I.inbox />} title="Chưa có thông báo">
          Khi có bạn bè thêm bill / thanh toán, thông báo sẽ xuất hiện ở đây.
        </Empty>
      ) : (
        notifications.map((n) => (
          <div
            key={n.id}
            className="activity-item"
            style={{ cursor: n.room ? "pointer" : "default" }}
            onClick={() =>
              n.room && navigate({ screen: "room", roomId: n.room.id })
            }
          >
            <div className="activity-icon">
              <span className="icon">
                {n.type === "settle" ? (
                  <I.handshake />
                ) : n.type === "expense" ? (
                  <I.receipt />
                ) : n.type === "join" ? (
                  <I.users />
                ) : n.type === "leave" ? (
                  <I.logout />
                ) : n.type === "remind" ? (
                  <I.bell />
                ) : n.type === "create" ? (
                  <I.doorOpen />
                ) : n.type === "delete" ? (
                  <I.trash />
                ) : (
                  <I.bell />
                )}
              </span>
            </div>
            <div className="activity-body">
              <div className="activity-text">{n.text}</div>
              <div className="activity-meta">
                {n.room && <>{n.room.name} · </>}
                {window.QC.timeAgo(n.createdAt)}
                {n.unread && (
                  <span
                    className="badge badge-accent"
                    style={{ marginLeft: 8 }}
                  >
                    Mới
                  </span>
                )}
              </div>
            </div>
          </div>
        ))
      )}
    </Modal>
  );
}

function Root() {
  return (
    <ToastHost>
      <App />
    </ToastHost>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Root />);
