/* ============================================================
   LIA · App shell — con autenticación Supabase real
   ============================================================ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "comoda",
  "cardStyle": "elevado",
  "licCard": "completa",
  "accent": "#009689"
}/*EDITMODE-END*/;

const ACCENTS = {
  "#009689": { a2: "#00c4a7", glow: "rgba(0,150,137,0.35)" },
  "#00b4a0": { a2: "#34d9c0", glow: "rgba(0,180,160,0.35)" },
  "#0ea5e9": { a2: "#67e8f9", glow: "rgba(14,165,233,0.35)" },
  "#4f46e5": { a2: "#a5b4fc", glow: "rgba(79,70,229,0.35)" },
};

/* ============================================================
   WRAPPER con auth state
   ============================================================ */
function AppRoot() {
  const [session, setSession]   = React.useState(null);
  const [loading, setLoading]   = React.useState(true);
  const [credits, setCreditsState] = React.useState(0);
  const [profile, setProfile]   = React.useState(null);

  /* Cargar sesión y perfil del usuario */
  async function cargarPerfil(user) {
    if (!window._sb || !user) return;
    window._currentUser = user;
    const { data } = await window._sb.from('profiles')
      .select('credits_balance, full_name, company_name')
      .eq('id', user.id)
      .single();
    if (data) {
      setCreditsState(data.credits_balance || 0);
      setProfile(data);
    }
  }

  React.useEffect(() => {
    if (!window._sb) {
      /* Sin Supabase — modo demo */
      setLoading(false);
      return;
    }
    window._sb.auth.getSession().then(({ data: { session } }) => {
      setSession(session);
      if (session) cargarPerfil(session.user);
      setLoading(false);
    });
    const { data: { subscription } } = window._sb.auth.onAuthStateChange((_event, session) => {
      setSession(session);
      if (session) cargarPerfil(session.user);
      else { setCreditsState(0); setProfile(null); window._currentUser = null; }
    });
    return () => subscription.unsubscribe();
  }, []);

  if (loading) return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--bg-deep)', display: 'grid', placeItems: 'center' }}>
      <div>
        <div className="lia-spin" style={{ width: 40, height: 40, margin: '0 auto 16px', border: '3px solid rgba(96,165,250,0.18)', borderTopColor: 'var(--accent-2)', borderRadius: '99px' }} />
        <div style={{ fontFamily: 'Syne', fontWeight: 700, color: 'var(--muted)', fontSize: 14, textAlign: 'center' }}>Iniciando LIA…</div>
      </div>
    </div>
  );

  if (!session && window.LIA_CONFIG.sbReady) {
    return <AuthScreen onAuth={(user) => { setSession({ user }); cargarPerfil(user); }} />;
  }

  return (
    <App
      session={session}
      credits={credits}
      setCredits={setCreditsState}
      profile={profile}
      setProfile={setProfile}
    />
  );
}

/* ============================================================
   DASHBOARD principal
   ============================================================ */
function App({ session, credits, setCredits, profile, setProfile }) {
  const D = window.LIA_DATA;
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  /* Persistir ruta y licitación activa en sessionStorage — sobreviven al refresh */
  const [route, setRouteState] = React.useState(() => {
    try { return sessionStorage.getItem('lia_route') || 'inicio'; } catch(e) { return 'inicio'; }
  });
  const [active, setActiveState] = React.useState(() => {
    try {
      const s = sessionStorage.getItem('lia_active');
      return s ? JSON.parse(s) : null;
    } catch(e) { return null; }
  });
  const [upload, setUpload] = React.useState(false);
  const [licCount, setLicCount] = React.useState(0);

  /* Cargar count real de licitaciones al montar */
  React.useEffect(() => {
    if (!window._sb || !user?.id) return;
    window._sb.from('licitaciones').select('id', { count: 'exact', head: true })
      .eq('user_id', user.id)
      .then(({ count }) => { if (count != null) setLicCount(count); });
  }, [user?.id]);

  function setRoute(r) {
    setRouteState(r);
    try { sessionStorage.setItem('lia_route', r); } catch(e) {}
  }
  function setActive(lic) {
    setActiveState(lic);
    try {
      if (lic) sessionStorage.setItem('lia_active', JSON.stringify({...lic, pdfBase64: null}));
      else sessionStorage.removeItem('lia_active');
    } catch(e) {}
  }

  /* Datos del usuario — real desde Supabase o mock */
  const user = session?.user;
  const userName = profile?.full_name
    || user?.user_metadata?.full_name
    || user?.email?.split('@')[0]
    || D.user.nombre;
  const userCompany = profile?.company_name
    || user?.user_metadata?.company_name
    || D.user.empresa;
  const userEmail = user?.email || D.user.email;
  const userIniciales = userName.split(' ').slice(0,2).map(n => n[0]).join('').toUpperCase() || 'LI';

  /* Avatar — se guarda en localStorage desde profile.jsx */
  const [userAvatar, setUserAvatar] = React.useState(() => {
    try { return localStorage.getItem('lia_avatar') || null; } catch(e) { return null; }
  });

  /* Actualizar créditos en el header al cambiar */
  React.useEffect(() => {
    const r = document.documentElement;
    r.setAttribute("data-density", t.density);
    r.setAttribute("data-cardstyle", t.cardStyle);
    const acc = ACCENTS[t.accent] || ACCENTS["#2563eb"];
    r.style.setProperty("--accent", t.accent);
    r.style.setProperty("--accent-2", acc.a2);
    r.style.setProperty("--accent-glow", acc.glow);
  }, [t.density, t.cardStyle, t.accent]);

  async function cerrarSesion() {
    if (window._sb) await window._sb.auth.signOut();
  }

  function openLic(lic) {
    setActive(lic);
    setRoute("detalle");
    document.querySelector(".content").scrollTop = 0;
  }
  function nav(r) { setRoute(r); setActive(null); }

  const navItems = [
    { group: "Principal", items: [
      { id: "inicio",       lab: "Inicio",          ico: "inicio" },
      { id: "licitaciones", lab: "Licitaciones",    ico: "licitaciones", badge: licCount || null },
      { id: "documentos",   lab: "Documentos",      ico: "documentos" },
    ]},
    { group: "Inteligencia LIA", items: [
      { id: "ley", lab: "Asistente legal", ico: "ley" },
    ]},
    { group: "Cuenta", items: [
      { id: "perfil",   lab: "Mi Perfil",  ico: "perfil" },
      { id: "creditos", lab: "Créditos",   ico: "creditos", badge: credits },
    ]},
  ];

  const titles = {
    inicio: "Inicio", licitaciones: "Licitaciones",
    documentos: "Documentos", ley: "Asistente legal · Ley 9986",
    creditos: "Créditos", perfil: "Mi Perfil", detalle: "Análisis de cartel"
  };

  return (
    <div className="shell">
      {/* SIDEBAR */}
      <aside className="sidebar">
        <div className="brand" style={{ padding: '12px 16px 8px' }}>
          <img src="/LIASI.jpeg" alt="LIA Solutions"
            style={{ width: '100%', maxHeight: 64, objectFit: 'contain', objectPosition: 'left', borderRadius: 8 }} />
        </div>

        {navItems.map((g) => (
          <div key={g.group}>
            <div className="nav-group-label">{g.group}</div>
            {g.items.map((it) => (
              <div key={it.id}
                className={"nav-item" + ((route === it.id || (route === "detalle" && it.id === "licitaciones")) ? " active" : "")}
                onClick={() => nav(it.id)}>
                <Icon name={it.ico} size={18} />
                <span>{it.lab}</span>
                {it.badge != null && <span className="nav-badge">{it.badge}</span>}
              </div>
            ))}
          </div>
        ))}

        <div className="sidebar-foot">
          <div className="nav-item"
            onClick={() => setUpload(true)}
            style={{ background: "rgba(37,99,235,0.1)", border: "1px solid var(--border-2)", color: "var(--text)", justifyContent: "center", marginBottom: 12 }}>
            <Icon name="plus" size={16} />
            <span style={{ fontFamily: "Syne", fontWeight: 700, fontSize: 12.5 }}>Analizar cartel</span>
          </div>

          {/* Tarjeta de usuario real */}
          <div className="user-card" style={{ position: 'relative' }}>
            <div className="avatar" style={{ overflow: 'hidden', padding: userAvatar ? 0 : undefined }}>
              {userAvatar
                ? <img src={userAvatar} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                : userIniciales}
            </div>
            <div className="user-meta" style={{ flex: 1, minWidth: 0 }}>
              <div className="n">{userName}</div>
              <div className="e">{userEmail}</div>
            </div>
            <button onClick={cerrarSesion} title="Cerrar sesión"
              style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: '1rem', padding: 4, borderRadius: 6 }}>
              <Icon name="back" size={15} />
            </button>
          </div>
        </div>
      </aside>

      {/* MAIN */}
      <div className="main">
        <header className="topbar">
          <div>
            {route === "detalle"
              ? <div className="crumb">Licitaciones <span style={{ opacity: .4 }}>/</span> <b>{active?.id}</b></div>
              : <div className="page-title">{titles[route]}</div>}
            {route === "detalle" && <div className="page-title" style={{ marginTop: 2 }}>{titles[route]}</div>}
          </div>
          <div className="search">
            <Icon name="search" size={15} />
            <input placeholder="Buscar licitación, SICOP, institución…" />
            <span className="kbd">⌘K</span>
          </div>
          <div className="credit-pill" onClick={() => nav("creditos")}>
            <span className="dot"></span>
            <span className="lab">Créditos</span>
            <span className="val">{credits}</span>
          </div>
        </header>

        <main className="content">
          <div className="content-inner">
            {route === "inicio"       && <ViewInicio onOpen={openLic} onNav={nav} onUpload={() => setUpload(true)} userName={userCompany} credits={credits} userId={user?.id} />}
            {route === "licitaciones" && <ViewLicitaciones onOpen={openLic} cardVariant={t.licCard} userId={user?.id} />}
            {route === "detalle"      && active && <ViewDetalle lic={active} onBack={() => nav("licitaciones")} credits={credits} setCredits={setCredits} userId={user?.id} />}
            {route === "documentos"   && <ViewDocumentos userId={user?.id} onOpen={openLic} onNav={nav} />}
            {route === "creditos"     && <ViewCreditos credits={credits} userId={user?.id} />}
            {route === "ley"          && <ViewLey userId={user?.id} />}
            {route === "perfil"       && <ViewPerfil userId={user?.id} onUpdate={({nombre,empresa,avatar}) => { setProfile(p => ({...p, full_name: nombre, company_name: empresa})); if (avatar) setUserAvatar(avatar); }} />}
          </div>
        </main>
      </div>

      <UploadModal open={upload} onClose={() => setUpload(false)} userId={user?.id}
        onDone={(lic) => { setUpload(false); if (lic) openLic(lic); else openLic(window.LIA_DATA.licitaciones[0]); }} />

      <TweaksPanel>
        <TweakSection label="Densidad" />
        <TweakRadio label="Información" value={t.density} options={["compacta", "comoda", "amplia"]} onChange={(v) => setTweak("density", v)} />
        <TweakSection label="Tarjetas" />
        <TweakRadio label="Estilo" value={t.cardStyle} options={["plano", "elevado", "glass", "contorno"]} onChange={(v) => setTweak("cardStyle", v)} />
        <TweakRadio label="Tarjeta de licitación" value={t.licCard} options={["completa", "minima"]} onChange={(v) => setTweak("licCard", v)} />
        <TweakSection label="Color de acento" />
        <TweakColor label="Acento" value={t.accent} options={Object.keys(ACCENTS)} onChange={(v) => setTweak("accent", v)} />
      </TweaksPanel>
    </div>
  );
}

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