// app.jsx — root shell, routing, shared state, tweaks
const { useState: aaState, useEffect: aaEffect, useRef: aaRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#155e4f", "#54a08b"],
  "radius": "Rounded",
  "density": "Regular",
  "font": "Serif",
  "dark": false,
  "device": "Desktop"
}/*EDITMODE-END*/;

const PALETTES = [
  ["#155e4f", "#54a08b"],  // emerald
  ["#1f3d63", "#5b8fc4"],  // slate blue
  ["#4a2d52", "#9a6fa6"],  // aubergine
  ["#6b4a2a", "#bf9a5a"],  // brass
  ["#2b2b2b", "#7a7a7a"],  // charcoal
];
const RADIUS_MAP = { Sharp: "5px", Rounded: "14px", Soft: "22px" };
const DENSITY_MAP = {
  Compact:  { pad: "12px", gap: "12px", fs: "13.8px" },
  Regular:  { pad: "16px", gap: "16px", fs: "15px" },
  Spacious: { pad: "22px", gap: "20px", fs: "15.5px" },
};
const FONT_MAP = {
  Serif:     { d: '"Spectral", Georgia, serif', b: '"Hanken Grotesk", system-ui, sans-serif' },
  Sans:      { d: '"Manrope", system-ui, sans-serif', b: '"Manrope", system-ui, sans-serif' },
  Editorial: { d: '"Cormorant Garamond", Georgia, serif', b: '"Hanken Grotesk", system-ui, sans-serif' },
};

const USER_NAV = [
  { key: "dashboard", label: "Dashboard", icon: "grid" },
  { key: "browse", label: "Browse", icon: "search" },
  { key: "saved", label: "Saved", icon: "heart" },
  { key: "requests", label: "Requests", icon: "calendar" },
  { key: "messages", label: "Messages", icon: "message" },
];
const ADMIN_NAV = [
  { key: "dashboard", label: "Overview", icon: "trending" },
  { key: "requests", label: "Requests", icon: "inbox" },
  { key: "users", label: "Members", icon: "users" },
  { key: "messages", label: "Messages", icon: "message" },
];

function NavItem({ item, active, onClick, badge }) {
  return (
    <button onClick={onClick} style={{
      display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "left",
      padding: "11px 13px", border: "none", cursor: "pointer", borderRadius: "var(--r-sm)",
      fontFamily: "var(--font-body)", fontSize: 14.5, fontWeight: active ? 600 : 500,
      background: active ? "var(--brand-soft)" : "transparent",
      color: active ? "var(--brand-ink)" : "var(--ink-2)", transition: "all .15s", position: "relative",
    }}>
      <Icon name={item.icon} size={19} stroke={active ? 2.3 : 2} />
      <span style={{ flex: 1 }}>{item.label}</span>
      {badge > 0 && <span style={{ background: "var(--brand)", color: "#fff", fontSize: 11, fontWeight: 700, minWidth: 19, height: 19, borderRadius: 99, display: "grid", placeItems: "center", padding: "0 5px" }}>{badge}</span>}
    </button>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [authed, setAuthed] = aaState(false);
  const [user, setUser] = aaState(null);
  const [fresh, setFresh] = aaState(false);
  const [role, setRole] = aaState("user");
  const [view, setView] = aaState("dashboard");
  const [prop, setProp] = aaState(null);
  const [saved, setSaved] = aaState(new Set(["p1", "p4", "p6", "p8"]));
  const [requests, setRequests] = aaState(window.CREDO.REQUESTS);
  const [toastMsg, setToastMsg] = aaState(null);
  const [reqModal, setReqModal] = aaState({ open: false });
  const toastTimer = aaRef(null);

  const isMobile = t.device === "Mobile";
  const userId = fresh ? "u9" : "u1";
  const den = DENSITY_MAP[t.density] || DENSITY_MAP.Regular;
  const font = FONT_MAP[t.font] || FONT_MAP.Serif;

  const tokens = {
    "--brand": t.palette[0], "--accent": t.palette[1],
    "--r": RADIUS_MAP[t.radius], "--pad": den.pad, "--gap": den.gap,
    "--font-display": font.d, "--font-body": font.b,
    fontSize: den.fs,
  };

  const toast = (msg) => {
    setToastMsg(msg);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToastMsg(null), 2800);
  };
  const navigate = (v) => { setView(v); };
  const signOut = () => { setAuthed(false); setRole("user"); setView("dashboard"); setProp(null); };
  const toggleSave = (id) => {
    setSaved(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  };
  const openProp = (p) => { setProp(p); setView("detail"); };
  const startRequest = (p, kind) => setReqModal({ open: true, kind, prop: p });
  const submitRequest = (payload) => {
    const n = requests.filter(r => r.kind === payload.kind).length + 1;
    const ref = (payload.kind === "Inspection" ? "INS-2" : "LSE-3") + (60 + n + Math.floor(Math.random() * 30));
    const newReq = {
      id: "r" + Date.now(), kind: payload.kind, ref, propId: payload.propId,
      user: user.name, userId, date: payload.date, slot: payload.slot,
      status: "Pending", created: "2026-06-15", note: payload.note || "—",
    };
    setRequests([newReq, ...requests]);
    setReqModal({ open: false });
    setView("requests");
    toast(`Request ${ref} submitted — we'll be in touch shortly`);
  };
  const advanceRequest = (id, status) => {
    setRequests(rs => rs.map(r => r.id === id ? { ...r, status } : r));
  };

  const ctx = { data: window.CREDO, user, saved, toggleSave, openProp, prop, requests, navigate, view, toast, isMobile, startRequest, advanceRequest, role, fresh, userId };
  const nav = role === "user" ? USER_NAV : ADMIN_NAV;
  const myOpenReqs = requests.filter(r => r.userId === userId && r.status !== "Completed").length;
  const adminOpenReqs = requests.filter(r => ["Pending", "In review"].includes(r.status)).length;

  const renderScreen = () => {
    if (role === "user") {
      switch (view) {
        case "dashboard": return <UserDashboard {...ctx} />;
        case "browse": return <BrowseScreen {...ctx} />;
        case "saved": return <SavedScreen {...ctx} />;
        case "requests": return <RequestsView {...ctx} />;
        case "messages": return <MessagesScreen {...ctx} />;
        case "detail": return <PropertyDetail {...ctx} />;
        default: return <UserDashboard {...ctx} />;
      }
    } else {
      switch (view) {
        case "dashboard": return <AdminDashboard {...ctx} />;
        case "requests": return <AdminRequests {...ctx} />;
        case "users": return <AdminUsers {...ctx} />;
        case "messages": return <AdminMessages {...ctx} />;
        default: return <AdminDashboard {...ctx} />;
      }
    }
  };

  // ---------- shell ----------
  const content = (
    <div style={{ maxWidth: role === "admin" ? 1180 : 1080, margin: "0 auto", width: "100%" }}>
      {renderScreen()}
    </div>
  );

  let shell;
  if (!authed) {
    shell = <AuthFlow isMobile={isMobile} onComplete={(u) => { setUser({ name: u.name, email: u.email }); setRole(u.role || "user"); setFresh(!!u.fresh); setSaved(u.fresh ? new Set() : new Set(["p1", "p4", "p6", "p8"])); setRequests(window.CREDO.REQUESTS); setView("dashboard"); setAuthed(true); }} />;
  } else if (isMobile) {
    shell = (
      <div style={{ display: "flex", flexDirection: "column", height: "100%", background: "var(--bg)" }}>
        {/* status bar */}
        <div style={{ height: 30, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 22px", fontSize: 12.5, fontWeight: 600, color: "var(--ink)", flexShrink: 0 }}>
          <span>9:41</span>
          <span style={{ display: "flex", gap: 5, alignItems: "center" }}><Icon name="bell" size={13} /></span>
        </div>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 18px", borderBottom: "1px solid var(--line)", flexShrink: 0, background: "var(--surface)" }}>
          <Logo size={21} />
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <button onClick={signOut} title="Sign out" style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", padding: 4, display: "inline-flex" }}><Icon name="logout" size={19} /></button>
          </div>
        </div>
        {/* main */}
        <div style={{ flex: 1, overflowY: "auto", padding: "20px 16px 24px" }}>{content}</div>
        {/* bottom nav */}
        <div style={{ display: "flex", borderTop: "1px solid var(--line)", background: "var(--surface)", flexShrink: 0, padding: "6px 6px 10px" }}>
          {nav.map(item => {
            const active = view === item.key || (item.key === "browse" && view === "detail");
            const badge = role === "user" && item.key === "requests" ? myOpenReqs : role === "admin" && item.key === "requests" ? adminOpenReqs : 0;
            return (
              <button key={item.key} onClick={() => navigate(item.key)} style={{
                flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4, padding: "7px 2px",
                border: "none", background: "transparent", cursor: "pointer", color: active ? "var(--brand)" : "var(--ink-3)",
                position: "relative",
              }}>
                <span style={{ position: "relative" }}>
                  <Icon name={item.icon} size={22} stroke={active ? 2.3 : 2} fill={active && item.key === "heart" ? "current" : "none"} />
                  {badge > 0 && <span style={{ position: "absolute", top: -5, right: -8, background: "var(--brand)", color: "#fff", fontSize: 9.5, fontWeight: 700, minWidth: 15, height: 15, borderRadius: 99, display: "grid", placeItems: "center" }}>{badge}</span>}
                </span>
                <span style={{ fontSize: 10.5, fontWeight: active ? 600 : 500 }}>{item.label}</span>
              </button>
            );
          })}
        </div>
      </div>
    );
  } else {
    shell = (
      <div style={{ display: "flex", height: "100%", background: "var(--bg)" }}>
        {/* sidebar */}
        <aside style={{ width: 250, flexShrink: 0, borderRight: "1px solid var(--line)", background: "var(--surface)", display: "flex", flexDirection: "column", padding: 18, gap: 18 }}>
          <div style={{ padding: "6px 8px" }}><Logo size={23} /></div>
          <nav style={{ display: "flex", flexDirection: "column", gap: 3 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-3)", padding: "6px 13px 4px" }}>{role === "user" ? "Menu" : "Console"}</div>
            {nav.map(item => (
              <NavItem key={item.key} item={item} active={view === item.key || (item.key === "browse" && view === "detail")}
                badge={item.key === "requests" ? (role === "user" ? myOpenReqs : adminOpenReqs) : 0}
                onClick={() => navigate(item.key)} />
            ))}
          </nav>
          <div style={{ marginTop: "auto", display: "flex", flexDirection: "column", gap: 4 }}>
            <NavItem item={{ label: "Settings", icon: "settings" }} onClick={() => {}} />
            <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 8px", borderTop: "1px solid var(--line)", marginTop: 6 }}>
              <Avatar name={role === "user" ? user.name : "Credeo Admin"} size={38} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{role === "user" ? user.name : "Credeo Admin"}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{role === "user" ? user.email : "Concierge desk"}</div>
              </div>
              <button onClick={signOut} title="Sign out" style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", padding: 4 }}><Icon name="logout" size={18} /></button>
            </div>
          </div>
        </aside>
        {/* main */}
        <main style={{ flex: 1, overflowY: "auto", minWidth: 0 }}>
          {/* top bar */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 32px", borderBottom: "1px solid var(--line)", position: "sticky", top: 0, background: "color-mix(in srgb, var(--bg) 86%, transparent)", backdropFilter: "blur(8px)", zIndex: 20 }}>
            <div style={{ fontSize: 13.5, color: "var(--ink-3)" }}>{role === "user" ? "Member portal" : "Admin console"} <span style={{ color: "var(--line-2)" }}>/</span> <span style={{ color: "var(--ink-2)", textTransform: "capitalize", fontWeight: 600 }}>{view === "detail" ? "Property" : view}</span></div>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <button style={{ position: "relative", background: "var(--surface)", border: "1px solid var(--line)", width: 40, height: 40, borderRadius: "50%", cursor: "pointer", display: "grid", placeItems: "center", color: "var(--ink-2)" }}>
                <Icon name="bell" size={18} />
                <span style={{ position: "absolute", top: 9, right: 10, width: 7, height: 7, borderRadius: 99, background: "var(--brand)", border: "1.5px solid var(--surface)" }} />
              </button>
              <Avatar name={role === "user" ? user.name : "Credeo Admin"} size={40} />
            </div>
          </div>
          <div style={{ padding: "32px" }}>{content}</div>
        </main>
      </div>
    );
  }

  return (
    <div className={"credo" + (t.dark ? " dark" : "")} style={tokens}>
      <div className={"stage" + (isMobile ? " mobile" : "")}>
        <div className={"viewport" + (isMobile ? " mobile" : "")}>
          {shell}
          <RequestModal open={reqModal.open} kind={reqModal.kind} prop={reqModal.prop} isMobile={isMobile}
            onClose={() => setReqModal({ open: false })} onSubmit={submitRequest} />
        </div>
      </div>

      <Toast toast={toastMsg} />

      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor label="Palette" value={t.palette} options={PALETTES} onChange={(v) => setTweak("palette", v)} />
        <TweakSection label="Typography" />
        <TweakRadio label="Pairing" value={t.font} options={["Serif", "Sans", "Editorial"]} onChange={(v) => setTweak("font", v)} />
        <TweakSection label="Shape & spacing" />
        <TweakRadio label="Corners" value={t.radius} options={["Sharp", "Rounded", "Soft"]} onChange={(v) => setTweak("radius", v)} />
        <TweakRadio label="Density" value={t.density} options={["Compact", "Regular", "Spacious"]} onChange={(v) => setTweak("density", v)} />
        <TweakSection label="Display" />
        <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak("dark", v)} />
        <TweakRadio label="Device" value={t.device} options={["Desktop", "Mobile"]} onChange={(v) => setTweak("device", v)} />
      </TweaksPanel>
    </div>
  );
}

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