/* App shell — header, navigation, role switcher, device frame */
const CKCtx = React.createContext(null);
const useCK = () => React.useContext(CKCtx);

const NAV = {
  dashboard: { th:'ภาพรวม', icon:'LayoutDashboard' },
  addjob:    { th:'เพิ่มงาน', icon:'CirclePlus' },
  queue:     { th:'คิวรายวัน', icon:'ClipboardList' },
  calendar:  { th:'ปฏิทิน', icon:'CalendarDays' },
  cover:     { th:'ใบปะหน้า', icon:'FileText' },
  assign:    { th:'มอบหมายช่าง', icon:'Truck' },
  mytasks:   { th:'งานของฉัน', icon:'Wrench' },
  manage:    { th:'จัดการระบบ', icon:'Settings' },
};
const ROLE_NAV = {
  sales: ['addjob','queue','calendar'],
  hq:    ['queue','calendar','cover','assign','addjob'],
  tech:  ['mytasks','calendar'],
  admin: ['dashboard','queue','calendar','cover','assign','manage'],
};

function Logo({ light }) {
  return (
    <div className="flex items-center gap-2.5">
      <span className={`grid place-items-center w-9 h-9 rounded-xl ${light?'bg-white/15 text-white':'bg-brand-600 text-white'}`}>
        <Icon name="Zap" size={20} sw={2.2} />
      </span>
      <div className="leading-tight">
        <div className={`text-[16px] font-medium ${light?'text-white':'text-slate-900'}`}>ChareonKit</div>
        <div className={`text-[10px] font-light ${light?'text-white/70':'text-slate-400'} -mt-0.5`}>ระบบจัดการคิวติดตั้ง</div>
      </div>
    </div>
  );
}

function RoleSwitcher() {
  const { role, setRole } = useCK();
  const [open,setOpen] = React.useState(false);
  const r = CK.ROLES[role];
  return (
    <div className="relative">
      <button onClick={()=>setOpen(o=>!o)} className="flex items-center gap-2 rounded-xl bg-white/12 hover:bg-white/20 text-white px-3 py-1.5 text-[13px] font-normal transition">
        <Icon name="UserCog" size={16} />
        <span className="hidden sm:inline">{r.label}</span>
        <span className="sm:hidden">{r.short}</span>
        <Icon name="ChevronDown" size={14} />
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={()=>setOpen(false)} />
          <div className="absolute right-0 mt-2 w-60 bg-white rounded-2xl shadow-pop ring-1 ring-slate-200 p-2 z-50">
            <div className="px-3 py-1.5 text-[11px] font-light text-slate-400">สลับมุมมองผู้ใช้ (demo)</div>
            {Object.values(CK.ROLES).map(x => (
              <button key={x.key} onClick={()=>{ setRole(x.key); setOpen(false); }}
                className={`w-full flex items-center gap-2.5 rounded-xl px-3 py-2 text-left text-[13px] transition ${role===x.key?'bg-brand-50 text-brand-700':'hover:bg-slate-50 text-slate-700'}`}>
                <span className={`grid place-items-center w-7 h-7 rounded-lg ${role===x.key?'bg-brand-600 text-white':'bg-slate-100 text-slate-500'}`}>
                  <Icon name={{sales:'Store',hq:'Building2',tech:'Wrench',admin:'ShieldCheck'}[x.key]} size={15} />
                </span>
                <span className="flex-1">{x.label}</span>
                {role===x.key && <Icon name="Check" size={15} />}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function DeviceToggle() {
  const { device, setDevice, tweaks } = useCK();
  const dark = tweaks.headerTheme==='dark';
  return (
    <div className="flex items-center rounded-xl bg-white/12 p-0.5" title="สลับมุมมอง Desktop / Mobile">
      {['desktop','mobile'].map(d => (
        <button key={d} onClick={()=>setDevice(d)}
          className={`grid place-items-center w-8 h-7 rounded-lg transition ${device===d?(dark?'bg-white text-slate-900':'bg-white text-brand-700'):'text-white/70 hover:text-white'}`}>
          <Icon name={d==='desktop'?'Monitor':'Smartphone'} size={15} />
        </button>
      ))}
    </div>
  );
}

function TopHeader({ compact }) {
  const { tweaks } = useCK();
  const dark = tweaks.headerTheme==='dark';
  return (
    <header className={`${dark?'bg-slate-950':'bg-brand-700'} text-white ${compact?'px-4 h-14':'px-5 h-16'} flex items-center justify-between shrink-0 z-30`}>
      <Logo light />
      <div className="flex items-center gap-2">
        <DeviceToggle />
        <RoleSwitcher />
        {!compact && (
          <button className="relative grid place-items-center w-9 h-9 rounded-xl bg-white/12 hover:bg-white/20 transition">
            <Icon name="Bell" size={18} />
            <span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-amber-300 ring-2 ring-brand-700" />
          </button>
        )}
      </div>
    </header>
  );
}

function Sidebar() {
  const { role, route, navigate } = useCK();
  const items = ROLE_NAV[role];
  return (
    <aside className="w-60 shrink-0 bg-white border-r border-slate-200 flex flex-col">
      <nav className="flex-1 p-3 space-y-1">
        <div className="px-3 py-2 text-[11px] font-light text-slate-400 uppercase tracking-wide">เมนูหลัก</div>
        {items.map(k => { const n = NAV[k]; const a = route===k;
          return (
            <button key={k} onClick={()=>navigate(k)}
              className={`w-full flex items-center gap-3 rounded-xl px-3 py-2.5 text-[14px] font-normal transition ${a?'bg-brand-50 text-brand-700 ring-1 ring-brand-200':'text-slate-600 hover:bg-slate-50'}`}>
              <Icon name={n.icon} size={18} sw={a?2.2:2} />
              {n.th}
            </button>
          );
        })}
      </nav>
      <div className="p-3 border-t border-slate-100">
        <div className="flex items-center gap-2.5 rounded-xl p-2 hover:bg-slate-50">
          <Avatar name={CK.ROLES[role].short} color="#0f172a" />
          <div className="min-w-0 flex-1">
            <div className="text-[13px] font-normal text-slate-700 truncate">{role==='admin'?'ผอ. ธนา':'สุดา รักงาน'}</div>
            <div className="text-[11px] font-light text-slate-400 truncate">{CK.ROLES[role].label}</div>
          </div>
          <Icon name="LogOut" size={16} className="text-slate-400" />
        </div>
      </div>
    </aside>
  );
}

function BottomNav() {
  const { role, route, navigate } = useCK();
  const all = ROLE_NAV[role];
  const [moreOpen,setMoreOpen] = React.useState(false);
  const overflow = all.length > 5;
  const primary = overflow ? all.slice(0,4) : all;
  const extra = overflow ? all.slice(4) : [];
  const extraActive = extra.includes(route);
  return (
    <>
      <nav className="shrink-0 bg-white border-t border-slate-200 flex items-stretch px-1 pb-[max(env(safe-area-inset-bottom),14px)]">
        {primary.map(k => { const n = NAV[k]; const a = route===k;
          return (
            <button key={k} onClick={()=>navigate(k)}
              className={`flex-1 flex flex-col items-center gap-0.5 py-2 transition ${a?'text-brand-700':'text-slate-400'}`}>
              <Icon name={n.icon} size={21} sw={a?2.3:2} />
              <span className="text-[10px] font-normal">{n.th}</span>
            </button>
          );
        })}
        {overflow && (
          <button onClick={()=>setMoreOpen(true)}
            className={`flex-1 flex flex-col items-center gap-0.5 py-2 transition ${extraActive?'text-brand-700':'text-slate-400'}`}>
            <Icon name="Menu" size={21} sw={extraActive?2.3:2} />
            <span className="text-[10px] font-normal">เพิ่มเติม</span>
          </button>
        )}
      </nav>
      <Modal open={moreOpen} onClose={()=>setMoreOpen(false)} title="เมนูเพิ่มเติม">
        <div className="p-3 space-y-1">
          {extra.map(k => { const n = NAV[k]; const a = route===k;
            return (
              <button key={k} onClick={()=>{ navigate(k); setMoreOpen(false); }}
                className={`w-full flex items-center gap-3 rounded-xl px-3 py-3 text-[14px] transition ${a?'bg-brand-50 text-brand-700 ring-1 ring-brand-200':'text-slate-700 hover:bg-slate-50'}`}>
                <span className={`grid place-items-center w-9 h-9 rounded-xl ${a?'bg-brand-600 text-white':'bg-slate-100 text-slate-500'}`}><Icon name={n.icon} size={18} /></span>
                {n.th}
              </button>
            );
          })}
        </div>
      </Modal>
    </>
  );
}

// iPhone 16 status bar — time left, room for Dynamic Island center, indicators right
function PhoneStatusBar({ dark }){
  return (
    <div className={`relative flex items-center justify-between pl-7 pr-6 h-[54px] shrink-0 text-[15px] font-medium tnum ${dark?'bg-slate-950 text-white':'bg-brand-700 text-white'}`}>
      <span className="pt-0.5 tracking-tight">9:41</span>
      <div className="flex items-center gap-1.5 pt-0.5">
        <Icon name="Signal" size={16} />
        <Icon name="Wifi" size={16} />
        <Icon name="BatteryFull" size={22} />
      </div>
    </div>
  );
}

// Layout: desktop = sidebar; mobile = phone frame
function Layout({ children }) {
  const { device, tweaks } = useCK();
  if (device === 'mobile') {
    const frame = tweaks.deviceFrame !== false; // default on
    const dark = tweaks.headerTheme==='dark';
    const W = frame ? 480 : 600;
    return (
      <div className="min-h-[100dvh] bg-slate-200/70 flex items-center justify-center p-0 sm:p-6">
        <div className={`relative mx-auto w-full ${frame?'device-shell':''}`} style={{ maxWidth: W }}>
          {frame && (
            <>
              <span className="ip-btn left ip-action" />
              <span className="ip-btn left ip-volup" />
              <span className="ip-btn left ip-voldn" />
              <span className="ip-btn right ip-camera" />
              <span className="ip-btn right ip-power" />
            </>
          )}
          <div className={`${frame?'device-screen':''} bg-slate-100 flex flex-col`} style={{ height: 'min(100dvh, 920px)' }}>
            {frame && <div className="dynamic-island" />}
            {frame && <PhoneStatusBar dark={dark} />}
            <TopHeader compact />
            <main className="flex-1 overflow-auto no-scrollbar">{children}</main>
            <BottomNav />
            {frame && <div className="home-indicator" style={{ background: dark ? 'rgba(255,255,255,.35)' : 'rgba(15,23,42,.28)' }} />}
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="h-[100dvh] flex flex-col">
      <TopHeader />
      <div className="flex-1 flex min-h-0">
        <Sidebar />
        <main className="flex-1 overflow-auto bg-[#f1f3f6]">{children}</main>
      </div>
    </div>
  );
}

Object.assign(window, { CKCtx, useCK, Layout, NAV, ROLE_NAV });
