// Main app — portal switcher + tweaks
const PORTALS = [
  { id: "A", label: "Portal A · Admin", subs: [
    { id: "A1", label: "Co-Founder", component: "PortalACofounder" },
    { id: "A2", label: "Marketing", component: "PortalAMarketing" },
    { id: "A3", label: "Support", component: "PortalASupport" },
  ]},
  { id: "B", label: "Portal B · Supplier", component: "PortalB" },
  { id: "C", label: "Portal C · Affiliate", component: "PortalC" },
  { id: "D", label: "Portal D · Nice Call", component: "PortalD" },
  { id: "E", label: "Portal E · Customer", component: "PortalE" },
];

function useHashRoute() {
  const [hash, setHash] = useState(() => window.location.hash.slice(1) || "A1");
  useEffect(() => {
    const onChange = () => setHash(window.location.hash.slice(1) || "A1");
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  const set = (h) => { window.location.hash = h; setHash(h); };
  return [hash, set];
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "primaryColor": "#1E4FD9",
  "theme": "light",
  "language": "th",
  "gpRate": 50
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = useHashRoute();
  const s = YJ.useStore();
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks → CSS
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme);
    const root = document.documentElement.style;
    root.setProperty("--accent", t.primaryColor);
    root.setProperty("--accent-2", shade(t.primaryColor, -10));
    root.setProperty("--accent-soft", lighten(t.primaryColor, 0.78));
  }, [t.theme, t.primaryColor]);

  let portal = PORTALS.find(p => route.startsWith(p.id)) || PORTALS[0];
  let CurrentComponent = null;
  if (portal.subs) {
    const sub = portal.subs.find(s => s.id === route) || portal.subs[0];
    CurrentComponent = window[sub.component];
  } else {
    CurrentComponent = window[portal.component];
  }

  const isPhonePortal = portal.id === "C";

  return (
    <ToastProvider>
      <div className="app-shell">
        <div className="topbar">
          <div className="topbar-inner">
            <div className="logo">
              <div className="logo-mark">YJ</div>
              <span>YJmall</span>
              <span className="pill" style={{ marginLeft: 8 }}>Prototype</span>
            </div>
            <div style={{ marginLeft: "auto" }}>
              <PortalNav route={route} setRoute={setRoute} />
            </div>
          </div>

          {portal.subs && (
            <div className="topbar-inner" style={{ paddingTop: 10 }}>
              <div className="portal-switch">
                {portal.subs.map(sub => (
                  <button key={sub.id} className={route === sub.id ? "active" : ""} onClick={() => setRoute(sub.id)}>{sub.label}</button>
                ))}
              </div>
              <div style={{ marginLeft: "auto", fontSize: 11, color: "var(--ink-3)" }}>
                Live data sync — เปลี่ยนพอร์ทัลแล้วข้อมูลซิงค์กันทั้งระบบ
              </div>
            </div>
          )}
        </div>

        <div className={isPhonePortal ? "" : "page"} style={isPhonePortal ? { flex: 1 } : null}>
          {CurrentComponent ? <CurrentComponent /> : <div>Component not found: {route}</div>}
        </div>

        <YJTweaksPanel t={t} setTweak={setTweak} />
      </div>
    </ToastProvider>
  );
}

function PortalNav({ route, setRoute }) {
  const activePortal = PORTALS.find(p => route.startsWith(p.id)) || PORTALS[0];
  return (
    <div className="portal-switch">
      {PORTALS.map(p => (
        <button key={p.id} className={activePortal.id === p.id ? "active" : ""}
          onClick={() => setRoute(p.subs ? p.subs[0].id : p.id)}>
          {p.label}
        </button>
      ))}
    </div>
  );
}

function YJTweaksPanel({ t, setTweak }) {
  const toast = useToast();
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="ธีม & สี">
        <TweakColor label="สีหลัก" value={t.primaryColor}
          options={["#1E4FD9", "#0A5E3E", "#7B61FF", "#E63946", "#FF6B35"]}
          onChange={v => setTweak("primaryColor", v)} />
        <TweakRadio label="โหมด" value={t.theme}
          options={[{ value: "light", label: "Light" }, { value: "dark", label: "Dark" }]}
          onChange={v => setTweak("theme", v)} />
      </TweakSection>

      <TweakSection label="ภาษา & GP">
        <TweakRadio label="ภาษา" value={t.language}
          options={[{ value: "th", label: "ไทย" }, { value: "en", label: "EN" }]}
          onChange={v => setTweak("language", v)} />
        <TweakRadio label="GP rate" value={String(t.gpRate)}
          options={[{ value: "40", label: "40%" }, { value: "50", label: "50%" }, { value: "60", label: "60%" }]}
          onChange={v => { setTweak("gpRate", Number(v)); YJ.actions.updateSettings({ gpDefault: Number(v) }); }} />
      </TweakSection>

      <TweakSection label="Mock data">
        <TweakButton label="รีเซ็ตข้อมูลทั้งหมด" onClick={() => {
          if (!window.confirm("รีเซ็ตข้อมูลทั้งหมดกลับเป็นค่าเริ่มต้น?")) return;
          YJ.resetState();
          toast.push("รีเซ็ตข้อมูลเรียบร้อย");
        }} secondary />
      </TweakSection>
    </TweaksPanel>
  );
}

// ===== Color helpers =====
function shade(hex, amount) {
  const c = hex.replace("#", "");
  const num = parseInt(c, 16);
  let r = (num >> 16) + amount;
  let g = ((num >> 8) & 0x00FF) + amount;
  let b = (num & 0x0000FF) + amount;
  r = clamp(r, 0, 255); g = clamp(g, 0, 255); b = clamp(b, 0, 255);
  return "#" + ((r << 16) | (g << 8) | b).toString(16).padStart(6, "0");
}
function lighten(hex, frac) {
  const c = hex.replace("#", "");
  const num = parseInt(c, 16);
  let r = (num >> 16), g = ((num >> 8) & 0xff), b = (num & 0xff);
  r = Math.round(r + (255 - r) * frac);
  g = Math.round(g + (255 - g) * frac);
  b = Math.round(b + (255 - b) * frac);
  return "#" + ((r << 16) | (g << 8) | b).toString(16).padStart(6, "0");
}

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