"use client";

import { useSyncExternalStore } from "react";
import { LayoutGrid, Rows3 } from "lucide-react";
import {
  DEFAULT_HOME_LAYOUT,
  readHomeLayout,
  setHomeLayout,
  subscribeHomeLayout,
  type HomeLayout,
} from "@/lib/homeLayout";

interface LayoutOption {
  id: HomeLayout;
  label: string;
  icon: typeof LayoutGrid;
  hint: string;
}

const OPTIONS: LayoutOption[] = [
  { id: "cockpit", label: "Cockpit", icon: LayoutGrid, hint: "the bento home" },
  { id: "classic", label: "Classic", icon: Rows3, hint: "the original home" },
];

// HomeLayoutToggle — compact segmented Cockpit | Classic control shown in the
// TopBar on the home route. Writing the preference re-renders <Home/> live
// via the homeLayout store subscription; no refresh needed.
export default function HomeLayoutToggle() {
  const layout = useSyncExternalStore(subscribeHomeLayout, readHomeLayout, () => DEFAULT_HOME_LAYOUT);

  return (
    <div
      role="group"
      aria-label="Home layout"
      className="inline-flex items-center gap-0.5 rounded-lg border border-[var(--panel-border)] p-0.5"
      style={{ background: "color-mix(in srgb, var(--cream) 2%, transparent)" }}
    >
      {OPTIONS.map((o) => {
        const active = o.id === layout;
        const Icon = o.icon;
        return (
          <button
            key={o.id}
            onClick={() => setHomeLayout(o.id)}
            aria-pressed={active}
            title={`${o.label} home, ${o.hint}`}
            className="focus-ring inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[10.5px] uppercase transition-colors"
            style={{
              color: active ? "var(--gold)" : "var(--cream-dim)",
              background: active ? "color-mix(in srgb, var(--gold) 10%, transparent)" : "transparent",
              border: `1px solid ${active ? "color-mix(in srgb, var(--gold) 30%, transparent)" : "transparent"}`,
              fontFamily: "'Manrope', sans-serif",
              fontWeight: 700,
              letterSpacing: "0.12em",
            }}
          >
            <Icon size={12} />
            <span className="hidden xl:inline">{o.label}</span>
          </button>
        );
      })}
    </div>
  );
}
