/* Main app shell: mobile + desktop split, tweaks panel, routing */

const { useState, useEffect, useMemo } = React;

// ─── DEVICE FRAMES ────────────────────────────────────────────────
const PhoneFrame = ({ children, label }) => (
  <div style={{ display:"flex", flexDirection:"column", alignItems:"center", gap:14 }}>
    <div style={{ position:"relative", width:380, height:780, borderRadius:48, background:"#000", padding:10, boxShadow:"0 30px 60px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.05)" }}>
      <div style={{ position:"absolute", top:18, left:"50%", transform:"translateX(-50%)", width:96, height:28, background:"#000", borderRadius:14, zIndex:60 }} />
      <div style={{ width:"100%", height:"100%", borderRadius:38, overflow:"hidden", background:"var(--bg)", position:"relative" }}>
        {/* Status bar */}
        <div style={{ position:"absolute", top:0, left:0, right:0, height:42, padding:"14px 28px 0", display:"flex", justifyContent:"space-between", alignItems:"center", color:"var(--ink)", fontSize:13, fontWeight:600, fontFamily:"var(--font-mono)", zIndex:55, pointerEvents:"none" }}>
          <span>9:41</span>
          <span style={{ display:"inline-flex", gap:5, alignItems:"center" }}>
            <span style={{ display:"inline-flex", gap:1.5 }}>
              {[3,5,7,9].map((h,i)=><span key={i} style={{ width:3, height:h, background:"currentColor", borderRadius:0.5 }} />)}
            </span>
            <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 4.5C3.5 2 6 1 7 1s3.5 1 6 3.5M3 6.5c1.5-1.5 3-2 4-2s2.5.5 4 2" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" /><circle cx="7" cy="8.5" r="0.8" fill="currentColor" /></svg>
            <span style={{ width:22, height:11, border:"1px solid currentColor", borderRadius:3, padding:1 }}>
              <span style={{ display:"block", width:"75%", height:"100%", background:"currentColor", borderRadius:1 }} />
            </span>
          </span>
        </div>
        {/* Content with status bar offset */}
        <div style={{ paddingTop:42, height:"100%", overflow:"auto" }}>{children}</div>
      </div>
    </div>
    <div className="t-mono" style={{ fontSize:11, color:"var(--ink-3)", textTransform:"uppercase", letterSpacing:"0.12em" }}>{label}</div>
  </div>
);

const DesktopFrame = ({ children, label }) => (
  <div style={{ display:"flex", flexDirection:"column", alignItems:"center", gap:14, flex:1, minWidth:0 }}>
    <div style={{ width:"100%", maxWidth:1180, height:780, borderRadius:14, background:"var(--bg)", overflow:"hidden", border:"1px solid var(--line)", boxShadow:"0 30px 60px rgba(0,0,0,0.4)", position:"relative", display:"flex", flexDirection:"column" }}>
      {/* Title bar */}
      <div style={{ height:32, background:"var(--surface)", borderBottom:"1px solid var(--line)", display:"flex", alignItems:"center", padding:"0 14px", gap:8, flexShrink:0 }}>
        <span style={{ display:"flex", gap:6 }}>
          <span style={{ width:11, height:11, borderRadius:"50%", background:"#ff5f57" }} />
          <span style={{ width:11, height:11, borderRadius:"50%", background:"#febc2e" }} />
          <span style={{ width:11, height:11, borderRadius:"50%", background:"#28c840" }} />
        </span>
        <div style={{ flex:1, textAlign:"center", color:"var(--ink-3)", fontSize:11, fontFamily:"var(--font-mono)" }}>tickettape.io</div>
      </div>
      <div style={{ flex:1, overflow:"auto" }}>{children}</div>
    </div>
    <div className="t-mono" style={{ fontSize:11, color:"var(--ink-3)", textTransform:"uppercase", letterSpacing:"0.12em" }}>{label}</div>
  </div>
);

// ─── MOBILE APP CONTENT ──────────────────────────────────────────
const MobileApp = ({ tweaks, route, navigate }) => {
  const [bottomNav, setBottomNav] = useState("home");

  const screenMap = {
    home: HomeScreen, search: SearchScreen, map: MapScreen, calendar: CalendarScreen,
    detail: DetailScreen, booking: BookingScreen, tickets: TicketsScreen,
    profile: ProfileScreen, ai: AIScreen, notifications: NotificationsScreen,
    organiser: OrganiserScreen, create: CreateEventScreen,
  };
  const Screen = screenMap[route.screen] || HomeScreen;

  // map bottom nav clicks to navigate
  useEffect(() => {
    if (["home","search","map","tickets","profile"].includes(route.screen)) setBottomNav(route.screen);
  }, [route.screen]);

  const showBottomNav = !["detail","booking","ai","create"].includes(route.screen);
  const showTopBar = ["home"].includes(route.screen);

  return (
    <div style={{ height:"100%", display:"flex", flexDirection:"column", position:"relative" }}>
      {showTopBar && <MobileTopBar city="Mumbai" onCityClick={()=>{}} onAI={()=>navigate("ai")} />}
      <div style={{ flex:1, overflowY:"auto", overflowX:"hidden", paddingBottom: showBottomNav ? 78 : 0 }}>
        <Screen tweaks={tweaks} isMobile={true} nav={navigate} eventId={route.params?.id} initialFilters={route.params?.filters} />
      </div>
      {showBottomNav && <BottomNav active={bottomNav} onNav={(id)=>navigate(id)} />}
    </div>
  );
};

// ─── DESKTOP APP CONTENT ─────────────────────────────────────────
const DesktopApp = ({ tweaks, route, navigate }) => {
  const screenMap = {
    home: HomeScreen, search: SearchScreen, map: MapScreen, calendar: CalendarScreen,
    detail: DetailScreen, booking: BookingScreen, tickets: TicketsScreen,
    profile: ProfileScreen, ai: AIScreen, notifications: NotificationsScreen,
    organiser: OrganiserScreen, create: CreateEventScreen,
  };
  const Screen = screenMap[route.screen] || HomeScreen;
  const navMap = { detail:"home", booking:"home", create:"organiser", calendar:"home", notifications:"home", ai:"home" };

  return (
    <div style={{ height:"100%", display:"flex", flexDirection:"column" }}>
      <DesktopNav active={navMap[route.screen] || route.screen} onNav={navigate} onAI={()=>navigate("ai")} />
      <div style={{ flex:1, overflowY:"auto" }}>
        <Screen tweaks={tweaks} isMobile={false} nav={navigate} eventId={route.params?.id} initialFilters={route.params?.filters} />
      </div>
    </div>
  );
};

// ─── PROTOTYPE WRAPPER (mobile + desktop side-by-side) ───────────
const Prototype = ({ tweaks, mobileRoute, setMobileRoute, desktopRoute, setDesktopRoute }) => {
  const navMobile = (screen, id, params) => setMobileRoute({ screen, params: id ? { id, ...params } : params });
  const navDesktop = (screen, id, params) => setDesktopRoute({ screen, params: id ? { id, ...params } : params });

  return (
    <div data-theme={tweaks.theme || "dark"} data-palette={tweaks.palette || "sunset"} style={{
      minHeight:"100vh",
      background: `radial-gradient(ellipse at top, color-mix(in oklab, var(--primary) 8%, var(--bg)), var(--bg))`,
      padding:"40px 32px 80px",
    }}>
      <div style={{ maxWidth:1700, margin:"0 auto" }}>
        {/* Header bar */}
        <header style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:36, flexWrap:"wrap", gap:16 }}>
          <div>
            <Logo />
            <div className="t-mono" style={{ fontSize:11, color:"var(--ink-3)", marginTop:8, textTransform:"uppercase", letterSpacing:"0.12em" }}>
              ● Hi-fi prototype · Mobile + Desktop · Connected flow
            </div>
          </div>
          <div style={{ display:"flex", gap:10, alignItems:"center" }}>
            <a href="canvas.html" className="btn btn-ghost"><I.layers cls="ico-sm" /> See 3 variations →</a>
          </div>
        </header>

        {/* Side-by-side */}
        <div style={{ display:"grid", gridTemplateColumns:"380px 1fr", gap:40, alignItems:"flex-start" }}>
          <PhoneFrame label="Mobile · iPhone">
            <MobileApp tweaks={tweaks} route={mobileRoute} navigate={navMobile} />
          </PhoneFrame>
          <DesktopFrame label="Desktop · Web">
            <DesktopApp tweaks={tweaks} route={desktopRoute} navigate={navDesktop} />
          </DesktopFrame>
        </div>

        {/* Quick screen jumps */}
        <div style={{ marginTop:36, padding:"20px 24px", background:"var(--surface)", border:"1px solid var(--line)", borderRadius:"var(--radius)" }}>
          <div className="t-eyebrow" style={{ marginBottom:12 }}>Jump to screen — click to update both views</div>
          <div style={{ display:"flex", flexWrap:"wrap", gap:8 }}>
            {[
              {k:"home", l:"Home / Discover"},
              {k:"search", l:"Browse"},
              {k:"map", l:"Map"},
              {k:"calendar", l:"Calendar"},
              {k:"detail", l:"Event detail", id:"e1"},
              {k:"booking", l:"Booking", id:"e1"},
              {k:"tickets", l:"Tickets wallet"},
              {k:"profile", l:"Profile"},
              {k:"ai", l:"AI Concierge"},
              {k:"notifications", l:"Notifications"},
              {k:"organiser", l:"Organiser"},
              {k:"create", l:"Create event"},
            ].map(s => {
              const active = mobileRoute.screen === s.k;
              return (
                <button key={s.k} onClick={()=>{ navMobile(s.k, s.id); navDesktop(s.k, s.id); }} style={{ padding:"7px 14px", borderRadius:999, background: active?"var(--ink)":"var(--bg)", color: active?"var(--bg)":"var(--ink-2)", border:`1px solid ${active?"var(--ink)":"var(--line)"}`, fontSize:12, fontWeight: active?600:500 }}>{s.l}</button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

window.Prototype = Prototype;
