// Mobile detection hook
function useIsMobile() {
  const [m, setM] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const h = () => setM(window.innerWidth < 768);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return m;
}
window.useIsMobile = useIsMobile;

// Sidebar navigation
function Sidebar({ page, setPage }){
  const isMobile = useIsMobile();
  const { USER } = window.KYOUDAI;
  const isAdmin = window.KYOUDAI.IS_ADMIN || false;
  const items = [
    { id:"dashboard", label:"Dashboard",  short:"Home",    icon:<I.dashboard style={{width:18,height:18}}/> },
    { id:"products",  label:"Products",   short:"Prods",   icon:<I.box style={{width:18,height:18}}/> },
    { id:"earnings",  label:"Earnings",   short:"Earn",    icon:<I.cash style={{width:18,height:18}}/> },
    { id:"content",   label:"Content Hub",short:"Content", icon:<I.play style={{width:18,height:18}}/>, hot:true },
    { id:"links",     label:"My Links",   short:"Links",   icon:<I.link style={{width:18,height:18}}/> },
    { id:"profile",   label:"Profile",    short:"Profile", icon:<I.user style={{width:18,height:18}}/> },
    ...(isAdmin ? [{ id:"admin", label:"Admin Panel", short:"Admin", icon:<I.settings style={{width:18,height:18}}/>, adminBadge:true }] : []),
  ];

  // ── MOBILE: bottom tab bar ─────────────────────────────────────────────────
  if (isMobile) {
    return (
      <nav style={{
        position:'fixed', bottom:0, left:0, right:0, zIndex:200,
        height:62, display:'flex', alignItems:'stretch',
        background:'rgba(11,15,26,0.97)', backdropFilter:'blur(20px)',
        WebkitBackdropFilter:'blur(20px)',
        borderTop:'1px solid var(--line)',
      }}>
        {items.map(it => {
          const active = page === it.id;
          return (
            <button key={it.id} onClick={() => setPage(it.id)} style={{
              flex:1, display:'flex', flexDirection:'column', alignItems:'center',
              justifyContent:'center', gap:3,
              background:'none', border:'none', cursor:'pointer', padding:'6px 2px',
              position:'relative',
            }}>
              {active && <span style={{
                position:'absolute', top:0, left:'50%', transform:'translateX(-50%)',
                width:28, height:2, borderRadius:2,
                background:'linear-gradient(90deg,#5B8CFF,#8A5BFF)',
              }}/>}
              <span style={{color: active ? '#6EA0FF' : 'var(--dim)', display:'flex', position:'relative'}}>
                {React.cloneElement(it.icon, {style:{width:20,height:20}})}
                {it.hot && <span style={{
                  position:'absolute', top:-2, right:-4,
                  width:6, height:6, borderRadius:99, background:'#FF6B8A', boxShadow:'0 0 6px #FF6B8A',
                }}/>}
              </span>
              <span style={{
                fontSize:9, fontFamily:"'JetBrains Mono',monospace", letterSpacing:'0.04em',
                color: active ? '#6EA0FF' : 'var(--dim)', textTransform:'uppercase',
              }}>{it.short}</span>
            </button>
          );
        })}
      </nav>
    );
  }

  // ── DESKTOP: sidebar ───────────────────────────────────────────────────────
  return (
    <aside style={{
      width:248, flexShrink:0, height:"100vh", padding:"22px 14px 18px",
      borderRight:"1px solid var(--line)",
      background:"linear-gradient(180deg, rgba(11,15,26,0.85), rgba(11,15,26,0.6))",
      backdropFilter:"blur(14px)",
      display:"flex", flexDirection:"column", gap:18,
      position:"relative",
    }}>
      {/* brand */}
      <div style={{display:"flex", alignItems:"center", gap:10, padding:"0 8px"}}>
        <img
          src="/logo.png"
          alt="Kyoudai"
          style={{width:34, height:34, borderRadius:10, flexShrink:0,
            boxShadow:"0 8px 24px -6px rgba(91,140,255,0.55)"}}
        />
        <div style={{lineHeight:1.15}}>
          <div style={{fontSize:14, fontWeight:700, letterSpacing:"-0.01em"}}>Kyoudai</div>
          <div className="mono" style={{fontSize:10, color:"var(--sub)", letterSpacing:"0.12em"}}>SELLER PLATFORM</div>
        </div>
      </div>

      {/* invite banner */}
      <div style={{
        padding:"12px 12px", borderRadius:12, position:"relative",
        background:"linear-gradient(135deg, rgba(91,140,255,0.1), rgba(138,91,255,0.08))",
        border:"1px solid rgba(91,140,255,0.22)",
        overflow:"hidden",
      }}>
        <div style={{display:"flex", alignItems:"center", gap:6, marginBottom:6}}>
          <I.lock style={{width:12,height:12, color:"#8AB0FF"}}/>
          <span className="mono" style={{fontSize:10, letterSpacing:"0.12em", color:"#8AB0FF"}}>INVITE-ONLY</span>
        </div>
        <div style={{fontSize:12, color:"var(--text)", fontWeight:500, lineHeight:1.35}}>
          You're one of <span style={{color:"#B89BFF", fontWeight:700}}>142</span> verified sellers this season.
        </div>
      </div>

      {/* nav */}
      <nav style={{display:"flex", flexDirection:"column", gap:2, flex:1}}>
        <div className="mono" style={{fontSize:10, color:"var(--dim)", letterSpacing:"0.14em", padding:"6px 12px", marginBottom:2}}>WORKSPACE</div>
        {items.map(it => (
          <div key={it.id} className={`navitem ${page===it.id?"active":""}`} onClick={() => setPage(it.id)}>
            <span className="icon">{it.icon}</span>
            <span style={{flex:1}}>{it.label}</span>
            {it.badge && <span className="mono" style={{fontSize:10, color:"var(--dim)"}}>{it.badge}</span>}
            {it.hot && <span style={{width:6, height:6, borderRadius:99, background:"#FF6B8A", boxShadow:"0 0 8px #FF6B8A"}}/>}
            {it.adminBadge && <span className="mono" style={{fontSize:9, padding:"2px 6px", borderRadius:4, background:"rgba(246,197,107,0.15)", color:"#F6C56B"}}>ADMIN</span>}
          </div>
        ))}
      </nav>

      {/* tier progress */}
      {(() => {
        const tp = USER.tierProgress || {};
        const pct = Math.round(tp.pct || 0);
        const toGo = tp.toGo || 0;
        const nextLabel = tp.nextLabel;
        return (
          <div style={{padding:"14px 12px", borderRadius:12, background:"rgba(255,255,255,0.02)", border:"1px solid var(--line)"}}>
            <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:8}}>
              <span className="mono" style={{fontSize:10, color:"var(--sub)", letterSpacing:"0.1em"}}>TIER PROGRESS</span>
              <span className="mono" style={{fontSize:10, color:"#F6C56B"}}>{pct}%</span>
            </div>
            <div style={{fontSize:12, color:"var(--text)", marginBottom:10, display:"flex", alignItems:"center", gap:6}}>
              <span style={{color:"#F6C56B", fontWeight:700}}>{USER.tier}</span>
              {nextLabel && <>
                <I.chevron style={{width:10, height:10, color:"var(--dim)"}}/>
                <span style={{color:"var(--sub)"}}>{nextLabel}</span>
              </>}
            </div>
            <div style={{height:4, background:"rgba(255,255,255,0.06)", borderRadius:99, overflow:"hidden"}}>
              <div style={{
                width:`${pct}%`, height:"100%",
                background:"linear-gradient(90deg, #F6C56B, #B89BFF)",
                boxShadow:"0 0 12px #F6C56B88"
              }}/>
            </div>
            {nextLabel
              ? <div style={{fontSize:11, color:"var(--sub)", marginTop:8}}>€{toGo.toLocaleString()} para desbloquear <span style={{color:"#B89BFF"}}>{nextLabel} ({nextLabel==='collector'?'5%':'7%'})</span></div>
              : <div style={{fontSize:11, color:"#F6C56B", marginTop:8}}>Tier máximo alcanzado 🏆</div>
            }
          </div>
        );
      })()}

      {/* user footer */}
      <div style={{display:"flex", alignItems:"center", gap:10, padding:"8px"}}>
        <Avatar initials={USER.avatar} size={32} tone="#8A5BFF"/>
        <div style={{flex:1, minWidth:0, lineHeight:1.2}}>
          <div style={{fontSize:13, fontWeight:600, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{USER.name}</div>
          <div className="mono" style={{fontSize:10, color:"var(--sub)"}}>@{USER.handle}</div>
        </div>
        <button title="Perfil & ajustes" onClick={() => setPage('profile')}
          style={{background:"none", border:"none", padding:4, cursor:"pointer", color:"var(--dim)", display:"grid", placeItems:"center", borderRadius:6, transition:"color .15s"}}
          onMouseEnter={e => e.currentTarget.style.color="var(--text)"}
          onMouseLeave={e => e.currentTarget.style.color="var(--dim)"}>
          <I.settings style={{width:16, height:16}}/>
        </button>
        <button title="Cerrar sesión" onClick={async () => { if(window.SUPABASE) { sessionStorage.clear(); await window.SUPABASE.auth.signOut(); } }}
          style={{background:"none", border:"none", padding:4, cursor:"pointer", color:"var(--dim)", display:"grid", placeItems:"center", borderRadius:6, transition:"color .15s", fontSize:15, lineHeight:1}}
          onMouseEnter={e => e.currentTarget.style.color="#FF8FA5"}
          onMouseLeave={e => e.currentTarget.style.color="var(--dim)"}>
          ⏻
        </button>
      </div>
    </aside>
  );
}

// Top header bar
function Topbar({ page, onOpenNotifs }){
  const isMobile = useIsMobile();
  const titles = {
    dashboard: ["Dashboard", "Welcome back. Your empire is compounding."],
    products: ["Products", "High-margin Japanese inventory, curated for elite sellers."],
    earnings: ["Earnings", "Every sale you've generated — pending and paid."],
    content: ["Content Hub", "Ready-to-post creative. Copy, paste, earn."],
    links: ["My Links", "Your generated affiliate links and live performance."],
    profile: ["Profile", "Account, payouts, referral identity y normas del programa."],
  };
  const [title, sub] = titles[page] || titles.dashboard;

  if (isMobile) {
    return (
      <header style={{
        display:"flex", alignItems:"center", justifyContent:"space-between",
        padding:"16px 18px 12px", borderBottom:"1px solid var(--line)",
        background:"linear-gradient(180deg, rgba(11,15,26,0.9), rgba(11,15,26,0.5))",
        backdropFilter:"blur(10px)",
        position:"sticky", top:0, zIndex:10,
      }}>
        <div style={{display:"flex", alignItems:"center", gap:10}}>
          <img src="/logo.png" alt="K" style={{width:28, height:28, borderRadius:7}}/>
          <div>
            <div style={{fontSize:17, fontWeight:700, letterSpacing:"-0.02em"}}>{title}</div>
          </div>
        </div>
        <span className="badge" style={{background:"rgba(138,91,255,0.12)", fontSize:10}}>
          <I.sparkle style={{width:9,height:9}}/>{(window.KYOUDAI.USER.tier||'').toUpperCase()}
        </span>
      </header>
    );
  }

  return (
    <header style={{
      display:"flex", alignItems:"center", justifyContent:"space-between",
      padding:"22px 32px 18px", borderBottom:"1px solid var(--line)",
      background:"linear-gradient(180deg, rgba(11,15,26,0.7), rgba(11,15,26,0.3))",
      backdropFilter:"blur(10px)",
      position:"sticky", top:0, zIndex:10,
    }}>
      <div>
        <div style={{display:"flex", alignItems:"center", gap:12}}>
          <h1 style={{margin:0, fontSize:24, fontWeight:700, letterSpacing:"-0.025em"}}>{title}</h1>
          <span className="badge badge-new" style={{background:"rgba(138,91,255,0.12)"}}>
            <I.sparkle style={{width:10,height:10}}/>{(window.KYOUDAI.USER.tier||'').toUpperCase()}
          </span>
        </div>
        <div style={{fontSize:13, color:"var(--sub)", marginTop:4}}>{sub}</div>
      </div>

      <div style={{display:"flex", alignItems:"center", gap:10}}>
        <div style={{
          display:"flex", alignItems:"center", gap:8, height:36, padding:"0 12px",
          border:"1px solid var(--line)", borderRadius:10, width:280,
          background:"rgba(255,255,255,0.02)",
        }}>
          <I.search style={{width:15, height:15, color:"var(--dim)"}}/>
          <input
            placeholder="Buscar productos…"
            style={{background:"transparent", border:"none", outline:"none", flex:1, color:"var(--text)", fontSize:13, fontFamily:"Sora"}}
            onChange={e => { window.kyoudaiSearch = e.target.value; window.dispatchEvent(new Event('kyoudai-search')); }}
            onKeyDown={e => { if(e.key==='Enter') { window.kyoudaiNav && window.kyoudaiNav('products'); } }}
          />
        </div>

        <button className="btn btn-primary" onClick={() => window.kyoudaiNav && window.kyoudaiNav('products')}>
          <I.bolt style={{width:14, height:14}}/>
          Promocionar
        </button>
      </div>
    </header>
  );
}

window.Sidebar = Sidebar;
window.Topbar = Topbar;
