/* B28 HospeX — app shell */
const NAV = [
  { key: "overview", icon: "dashboard", label: "Visão geral", title: "Visão geral", sub: "Desempenho consolidado da Rede Costa Viva" },
  { key: "surveys", icon: "sentiment_satisfied", label: "Pesquisas", title: "Pesquisas de satisfação", sub: "NPS, áreas e análise semântica das respostas" },
  { key: "reputation", icon: "reviews", label: "Reputação", title: "Reputação online", sub: "Avaliações centralizadas, Smart Replies e IRO" },
  { key: "cases", icon: "flag", label: "Casos", title: "Gestão de casos", sub: "Ocorrências, responsáveis e acompanhamento" },
  { key: "concierge", icon: "forum", label: "Concierge IA", title: "Concierge IA", sub: "Assistente virtual no WhatsApp, 24/7" },
  { key: "mobile", icon: "smartphone", label: "App mobile", title: "App mobile", sub: "Operação e hóspede na palma da mão" },
];
const NAV_SECONDARY = [
  { key: "reports", icon: "insights", label: "Relatórios", title: "Relatórios", sub: "Modelos, exportação e envios automáticos" },
  { key: "integrations", icon: "hub", label: "Integrações", title: "Integrações", sub: "OTAs, 50+ PMS, mensageria e BI" },
  { key: "settings", icon: "settings", label: "Configurações", title: "Configurações", sub: "Conta, equipe, unidades e automações" },
];
const ALL_NAV = [...NAV, ...NAV_SECONDARY];

function Logo() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
      <div style={{ width: 40, height: 40, borderRadius: 12, background: "var(--primary-fixed)", display: "grid", placeItems: "center", flexShrink: 0 }}>
        <span className="font-headline" style={{ fontSize: 15, fontWeight: 800, color: "var(--on-primary-fixed)", letterSpacing: "-0.04em" }}>B28</span>
      </div>
      <div>
        <div className="font-headline" style={{ fontSize: 17, fontWeight: 800, color: "#fff", letterSpacing: "-0.02em", lineHeight: 1 }}>HospeX</div>
        <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--primary-fixed-dim)", marginTop: 3 }}>Guest Experience</div>
      </div>
    </div>
  );
}

function Sidebar({ view, setView, onLogout, user }) {
  const [menu, setMenu] = useState(false);
  return (
    <aside style={{ width: 248, background: "var(--sidebar-bg)", display: "flex", flexDirection: "column", flexShrink: 0, position: "sticky", top: 0, height: "100vh" }}>
      <div style={{ padding: "26px 22px 22px" }}><Logo /></div>

      <nav style={{ flex: 1, padding: "8px 14px", display: "flex", flexDirection: "column", gap: 3 }}>
        <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(255,255,255,0.38)", padding: "10px 12px 6px" }}>Plataforma</div>
        {NAV.map(item => {
          const on = view === item.key;
          return (
            <button key={item.key} onClick={() => setView(item.key)} className="hx-nav"
              style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 12px", borderRadius: 11, border: "none", cursor: "pointer", textAlign: "left", width: "100%",
                background: on ? "var(--primary)" : "transparent", color: on ? "#fff" : "rgba(255,255,255,0.72)" }}>
              <Icon name={item.icon} size={20} fill={on ? 1 : 0} />
              <span style={{ fontSize: 13.5, fontWeight: on ? 700 : 600, fontFamily: "var(--font-headline)" }}>{item.label}</span>
            </button>
          );
        })}

        <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(255,255,255,0.38)", padding: "18px 12px 6px" }}>Recursos transversais</div>
        {NAV_SECONDARY.map(item => {
          const on = view === item.key;
          return (
            <button key={item.key} onClick={() => setView(item.key)} className="hx-nav"
              style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 12px", borderRadius: 11, border: "none", cursor: "pointer", textAlign: "left", width: "100%",
                background: on ? "var(--primary)" : "transparent", color: on ? "#fff" : "rgba(255,255,255,0.72)" }}>
              <Icon name={item.icon} size={20} fill={on ? 1 : 0} />
              <span style={{ fontSize: 13.5, fontWeight: on ? 700 : 600, fontFamily: "var(--font-headline)" }}>{item.label}</span>
            </button>
          );
        })}
      </nav>

      <div style={{ padding: 14, borderTop: "1px solid rgba(255,255,255,0.08)", position: "relative" }}>
        <button onClick={() => setMenu(m => !m)} className="hx-nav" style={{ display: "flex", alignItems: "center", gap: 11, padding: "8px 10px", width: "100%", border: "none", background: "transparent", cursor: "pointer", borderRadius: 11, textAlign: "left" }}>
          <Avatar name={user?.full_name || "Helena Braga"} size={38} bg="var(--primary-container)" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#fff", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user?.full_name || "Helena Braga"}</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)" }}>{user?.email || "Diretora de Experiência"}</div>
          </div>
          <Icon name="unfold_more" size={18} style={{ color: "rgba(255,255,255,0.5)" }} />
        </button>
        {menu && (
          <>
            <div onClick={() => setMenu(false)} style={{ position: "fixed", inset: 0, zIndex: 40 }}></div>
            <div style={{ position: "absolute", bottom: "calc(100% - 6px)", left: 14, right: 14, background: "var(--surface-container-lowest)", borderRadius: 14, boxShadow: "var(--shadow-md)", border: "1px solid var(--outline-variant)", padding: 8, zIndex: 50 }}>
              <button onClick={() => { setView("settings"); setMenu(false); }} className="hx-opt" style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "10px 12px", borderRadius: 10, border: "none", cursor: "pointer", textAlign: "left", background: "transparent" }}>
                <Icon name="settings" size={18} style={{ color: "var(--on-surface-variant)" }} /><span style={{ fontSize: 13, fontWeight: 600 }}>Configurações</span>
              </button>
              <button onClick={onLogout} className="hx-opt" style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "10px 12px", borderRadius: 10, border: "none", cursor: "pointer", textAlign: "left", background: "transparent", color: "var(--error)" }}>
                <Icon name="logout" size={18} /><span style={{ fontSize: 13, fontWeight: 700 }}>Sair</span>
              </button>
            </div>
          </>
        )}
      </div>
    </aside>
  );
}

function HotelSelect({ orgName, hotels, activeHotelId, setActiveHotelId }) {
  const [open, setOpen] = useState(false);

  const selectedHotel = hotels.find(h => h.id === activeHotelId) || null;
  const label = activeHotelId ? (selectedHotel?.name || 'Hotel') : (orgName || 'Organização');
  const subtitle = !activeHotelId && hotels.length ? `· ${hotels.length} unidades` : '';

  const opts = [
    { id: null, name: 'Toda a rede' },
    ...hotels.map(h => ({ id: h.id, name: h.name }))
  ];

  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 14px", borderRadius: 999, border: "1px solid var(--outline-variant)", background: "var(--surface-container-lowest)", cursor: "pointer" }}>
        <Icon name="apartment" size={17} style={{ color: "var(--primary)" }} fill={1} />
        <span style={{ fontSize: 13, fontWeight: 700 }}>{label}</span>
        <span style={{ fontSize: 11, color: "var(--on-surface-variant)" }}>{subtitle}</span>
        <Icon name="expand_more" size={18} style={{ color: "var(--on-surface-variant)" }} />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 40 }}></div>
          <div style={{ position: "absolute", top: "calc(100% + 8px)", left: 0, width: 260, background: "var(--surface-container-lowest)", borderRadius: 14, boxShadow: "var(--shadow-md)", border: "1px solid var(--outline-variant)", padding: 8, zIndex: 50 }}>
            {opts.map((o, i) => {
              const selected = (activeHotelId || null) === (o.id || null);
              return (
                <button key={i} onClick={() => { setActiveHotelId(o.id); setOpen(false); }} className="hx-opt"
                  style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "10px 12px", borderRadius: 10, border: "none", cursor: "pointer", textAlign: "left", background: selected ? "var(--surface-container-low)" : "transparent" }}>
                  <Icon name={o.id ? "apartment" : "hub"} size={17} style={{ color: selected ? "var(--primary)" : "var(--on-surface-variant)" }} fill={selected ? 1 : 0} />
                  <span style={{ fontSize: 13, fontWeight: selected ? 700 : 500, flex: 1 }}>{o.name}</span>
                  {selected && <Icon name="check" size={16} style={{ color: "var(--primary)" }} />}
                </button>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

function Topbar({ meta, orgName, hotels, activeHotelId, setActiveHotelId }) {
  const [period, setPeriod] = useState("30 dias");
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 30, background: "color-mix(in srgb, var(--background) 86%, transparent)", backdropFilter: "blur(12px)", borderBottom: "1px solid var(--outline-variant)", padding: "18px 36px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20 }}>
      <div>
        <h1 className="font-headline" style={{ margin: 0, fontSize: 23, fontWeight: 800, letterSpacing: "-0.025em" }}>{meta.title}</h1>
        <p style={{ margin: "3px 0 0", fontSize: 13, color: "var(--on-surface-variant)" }}>{meta.sub}</p>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <HotelSelect orgName={orgName} hotels={hotels} activeHotelId={activeHotelId} setActiveHotelId={setActiveHotelId} />
        <div style={{ display: "flex", background: "var(--surface-container-low)", borderRadius: 999, padding: 3 }}>
          {["7 dias", "30 dias", "Ano"].map(p => (
            <button key={p} onClick={() => setPeriod(p)} style={{ padding: "7px 14px", borderRadius: 999, border: "none", cursor: "pointer", fontSize: 12.5, fontWeight: 700, fontFamily: "var(--font-headline)", background: period === p ? "var(--surface-container-lowest)" : "transparent", color: period === p ? "var(--on-surface)" : "var(--on-surface-variant)", boxShadow: period === p ? "var(--shadow-sm)" : "none" }}>{p}</button>
          ))}
        </div>
        <button style={{ width: 42, height: 42, borderRadius: 999, border: "1px solid var(--outline-variant)", background: "var(--surface-container-lowest)", cursor: "pointer", display: "grid", placeItems: "center", position: "relative" }}>
          <Icon name="notifications" size={20} />
          <span style={{ position: "absolute", top: 8, right: 9, width: 8, height: 8, borderRadius: 999, background: "var(--error)", border: "2px solid var(--surface-container-lowest)" }}></span>
        </button>
      </div>
    </header>
  );
}

function App() {
  const [authed, setAuthed] = useState(false);
  const [user, setUser] = useState(null);
  const [view, setView] = useState("overview");
  const [orgName, setOrgName] = useState('Organização');
  const [hotels, setHotels] = useState([]);
  const [activeHotelId, setActiveHotelId] = useState(null);
  const meta = ALL_NAV.find(n => n.key === view) || ALL_NAV[0];
  const go = setView;

  useEffect(() => {
    const savedUser = localStorage.getItem("hx-user");
    if (savedUser) {
      setUser(JSON.parse(savedUser));
      setAuthed(true);
    } else if (localStorage.getItem("hx-authed") === "1") {
      setAuthed(true);
    }
    
    const savedView = localStorage.getItem("hx-view");
    if (savedView && ALL_NAV.find(n => n.key === savedView)) setView(savedView);
  }, []);

  useEffect(() => {
    let canceled = false;
    async function load() {
      try {
        const hotelsRes = await fetch('/api/hotels');
        const hotelsJson = await hotelsRes.json();
        const list = Array.isArray(hotelsJson?.hotels) ? hotelsJson.hotels : [];

        if (canceled) return;
        setHotels(list);

        const saved = localStorage.getItem('hx-hotel-id');
        if (saved && saved !== 'all') {
          const found = list.find(h => h.id === saved);
          setActiveHotelId(found ? found.id : null);
        }
      } catch (e) {
        if (!canceled) setHotels([]);
      }
    }
    load();
    return () => { canceled = true; };
  }, []);

  useEffect(() => {
    localStorage.setItem('hx-hotel-id', activeHotelId ? activeHotelId : 'all');
  }, [activeHotelId]);

  useEffect(() => { if (authed) localStorage.setItem("hx-view", view); }, [view, authed]);

  function login(userData) { 
    localStorage.setItem("hx-authed", "1"); 
    if (userData) {
      setUser(userData);
      localStorage.setItem("hx-user", JSON.stringify(userData));
    }
    setAuthed(true); 
  }
  
  function logout() { 
    localStorage.removeItem("hx-authed"); 
    localStorage.removeItem("hx-user");
    setUser(null);
    setAuthed(false); 
  }

  if (!authed) return <Login onEnter={login} />;

  const views = {
    overview: <ViewOverview hotelId={activeHotelId} go={go} />,
    surveys: <ViewSurveys hotelId={activeHotelId} />,
    reputation: <ViewReputation hotelId={activeHotelId} />,
    cases: <ViewCases hotelId={activeHotelId} />,
    concierge: <ViewConcierge hotelId={activeHotelId} />,
    mobile: <ViewMobile hotelId={activeHotelId} />,
    reports: <ViewReports hotelId={activeHotelId} />,
    integrations: <ViewIntegrations hotelId={activeHotelId} />,
    settings: <ViewSettings hotelId={activeHotelId} onLogout={logout} />,
  };

  return (
    <div style={{ display: "flex", minHeight: "100vh" }}>
      <Sidebar view={view} setView={setView} onLogout={logout} user={user} />
      <main style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        <Topbar meta={meta} orgName={orgName} hotels={hotels} activeHotelId={activeHotelId} setActiveHotelId={setActiveHotelId} />
        <div key={view} style={{ padding: "28px 36px 64px", maxWidth: 1320, width: "100%", animation: "hxFade .28s ease" }}>
          {views[view]}
        </div>
      </main>
    </div>
  );
}

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