// app/chrome.jsx — device frames (laptop / iPad / iPhone), device switcher,
// responsive navigation (top header + mobile bottom nav), and the Shell wrapper.

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC, useCallback: useCallbackC } = React;

// ─────────────────────────────────────────────────────────────
// Fit-to-viewport scaling
// ─────────────────────────────────────────────────────────────
function useFitScale(outerW, outerH, { padX = 40, padY = 96, max = 1.4 } = {}) {
  const [scale, setScale] = useStateC(1);
  useEffectC(() => {
    const compute = () => {
      const availW = window.innerWidth - padX;
      const availH = window.innerHeight - padY;
      const k = Math.min(availW / outerW, availH / outerH, max);
      setScale(Math.max(0.12, k));
    };
    compute();
    window.addEventListener('resize', compute);
    return () => window.removeEventListener('resize', compute);
  }, [outerW, outerH, padX, padY, max]);
  return scale;
}

// ─────────────────────────────────────────────────────────────
// The device-switcher bar (lives outside the scaled frame)
// ─────────────────────────────────────────────────────────────
const DEVICE_ICONS = {
  laptop: (s) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="12" rx="1.5" /><path d="M2 20h20" /></svg>
  ),
  ipad: (s) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="3" width="16" height="18" rx="2" /><path d="M11 18h2" /></svg>
  ),
  iphone: (s) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <rect x="7" y="2" width="10" height="20" rx="2.5" /><path d="M11 18.5h2" /></svg>
  ),
};

function DeviceSwitcher() {
  const { device, pickDevice, exitDevice, resetAll } = useApp();
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, height: 52, zIndex: 50,
      display: 'flex', alignItems: 'center', gap: 16, padding: '0 18px',
      background: 'rgba(8,8,10,0.72)', backdropFilter: 'blur(16px)',
      borderBottom: '1px solid rgba(255,255,255,0.06)',
      fontFamily: 'Bricolage Grotesque',
    }}>
      <button onClick={exitDevice} title="Back to device chooser" style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        background: 'transparent', border: 'none', cursor: 'pointer',
        color: 'rgba(244,241,233,0.55)', fontFamily: 'Bricolage Grotesque',
        fontSize: 12, fontWeight: 500, letterSpacing: '0.01em', padding: '6px 4px',
      }}>
        <span style={{ fontSize: 15 }}>‹</span> Chooser
      </button>

      <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 4 }}>
        <span style={{ fontFamily: 'Bricolage Grotesque', fontWeight: 700, fontSize: 16,
          color: '#f4f1e9', letterSpacing: '-0.045em' }}>luis</span>
        <span style={{ fontFamily: 'Spectral', fontStyle: 'italic', fontWeight: 500,
          fontSize: 16, color: '#f0a850', letterSpacing: '-0.015em' }}>cooks.</span>
      </div>

      <div style={{ flex: 1 }} />

      <div style={{ display: 'inline-flex', gap: 4, padding: 4, borderRadius: 999,
        background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)' }}>
        {['laptop', 'ipad', 'iphone'].map((d) => {
          const active = device === d;
          return (
            <button key={d} onClick={() => pickDevice(d)} title={d} style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              padding: '6px 12px', borderRadius: 999, cursor: 'pointer',
              border: '1px solid ' + (active ? 'rgba(240,168,80,0.4)' : 'transparent'),
              background: active ? 'rgba(240,168,80,0.14)' : 'transparent',
              color: active ? '#f0a850' : 'rgba(244,241,233,0.5)',
              fontFamily: 'Bricolage Grotesque', fontSize: 12, fontWeight: 600,
              letterSpacing: '0.01em', textTransform: 'capitalize',
            }}>
              {DEVICE_ICONS[d](15)}
              {d === 'iphone' ? 'iPhone' : d === 'ipad' ? 'iPad' : 'Laptop'}
            </button>
          );
        })}
      </div>

      <button onClick={resetAll} title="Reset all saved state" style={{
        background: 'transparent', border: '1px solid rgba(255,255,255,0.08)',
        borderRadius: 999, cursor: 'pointer', color: 'rgba(244,241,233,0.45)',
        fontFamily: 'Bricolage Grotesque', fontSize: 11, fontWeight: 500,
        padding: '6px 12px', letterSpacing: '0.02em',
      }}>Reset demo</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Device frames — each renders the app (children) inside a fixed screen
// ─────────────────────────────────────────────────────────────
function ScreenSlot({ w, h, radius, children }) {
  return (
    <div style={{
      width: w, height: h, borderRadius: radius, overflow: 'hidden',
      background: '#0c0c0e', position: 'relative', flexShrink: 0,
      boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.6)',
    }}>{children}</div>
  );
}

function LaptopFrame({ children }) {
  const { w, h } = DEVICE_SCREEN.laptop;
  const lidPadX = 16, lidPadTop = 16, chin = 30;
  const lidW = w + lidPadX * 2;
  const lidH = lidPadTop + h + chin;
  const baseExtra = 130;
  const baseW = lidW + baseExtra;
  const baseH = 22;
  const outerW = baseW;
  const outerH = lidH + baseH;
  const scale = useFitScale(outerW, outerH);

  return (
    <div style={{ width: outerW * scale, height: outerH * scale }}>
      <div style={{ width: outerW, height: outerH, transform: `scale(${scale})`,
        transformOrigin: 'top left', display: 'flex', flexDirection: 'column',
        alignItems: 'center' }}>
        {/* Lid */}
        <div style={{
          width: lidW, padding: `${lidPadTop}px ${lidPadX}px ${chin}px`,
          background: 'linear-gradient(180deg, #2a2a2e, #1a1a1d)',
          borderRadius: '24px 24px 8px 8px',
          boxShadow: '0 40px 90px rgba(0,0,0,0.65), inset 0 1px 0 rgba(255,255,255,0.10), inset 0 0 0 1px rgba(0,0,0,0.5)',
          position: 'relative', boxSizing: 'content-box',
        }}>
          {/* camera */}
          <div style={{ position: 'absolute', top: 7, left: '50%', transform: 'translateX(-50%)',
            width: 6, height: 6, borderRadius: 999, background: '#0c0c0e',
            boxShadow: 'inset 0 0 0 1.5px #34343a' }} />
          <ScreenSlot w={w} h={h} radius={6}>{children}</ScreenSlot>
          {/* chin logo */}
          <div style={{ position: 'absolute', bottom: 9, left: '50%', transform: 'translateX(-50%)',
            display: 'inline-flex', alignItems: 'baseline', gap: 3, opacity: 0.55 }}>
            <span style={{ fontFamily: 'Bricolage Grotesque', fontWeight: 700, fontSize: 11,
              color: '#cfc9bb', letterSpacing: '-0.04em' }}>luis</span>
            <span style={{ fontFamily: 'Spectral', fontStyle: 'italic', fontWeight: 500,
              fontSize: 11, color: '#f0a850', letterSpacing: '-0.015em' }}>cooks.</span>
          </div>
        </div>
        {/* Base / hinge */}
        <div style={{ width: baseW, height: baseH,
          background: 'linear-gradient(180deg, #2c2c30 0%, #19191c 55%, #0e0e10 100%)',
          borderRadius: '4px 4px 12px 12px',
          boxShadow: '0 22px 40px rgba(0,0,0,0.55)', position: 'relative' }}>
          <div style={{ position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)',
            width: 160, height: 8, borderRadius: '0 0 8px 8px',
            background: 'linear-gradient(180deg, #141417, #232327)' }} />
        </div>
      </div>
    </div>
  );
}

function IpadFrame({ children }) {
  const { w, h } = DEVICE_SCREEN.ipad;
  const bezel = 26;
  const outerW = w + bezel * 2;
  const outerH = h + bezel * 2;
  const scale = useFitScale(outerW, outerH);
  return (
    <div style={{ width: outerW * scale, height: outerH * scale }}>
      <div style={{ width: outerW, height: outerH, transform: `scale(${scale})`,
        transformOrigin: 'top left', position: 'relative',
        background: 'linear-gradient(155deg, #2a2a2e, #131316)',
        borderRadius: 40,
        boxShadow: '0 40px 90px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.10), inset 0 0 0 1px rgba(0,0,0,0.5)',
        padding: bezel, boxSizing: 'border-box',
        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {/* camera on long top edge */}
        <div style={{ position: 'absolute', top: bezel / 2 - 3, left: '50%',
          transform: 'translateX(-50%)', width: 6, height: 6, borderRadius: 999,
          background: '#0c0c0e', boxShadow: 'inset 0 0 0 1.5px #34343a' }} />
        <ScreenSlot w={w} h={h} radius={18}>{children}</ScreenSlot>
      </div>
    </div>
  );
}

function IphoneFrame({ children }) {
  const { w, h } = DEVICE_SCREEN.iphone;
  const bezel = 13;
  const outerW = w + bezel * 2;
  const outerH = h + bezel * 2;
  const scale = useFitScale(outerW, outerH, { max: 1.35 });
  return (
    <div style={{ width: outerW * scale, height: outerH * scale }}>
      <div style={{ width: outerW, height: outerH, transform: `scale(${scale})`,
        transformOrigin: 'top left', position: 'relative',
        background: 'linear-gradient(155deg, #303034, #141417)',
        borderRadius: 58,
        boxShadow: '0 40px 90px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.12), inset 0 0 0 1px rgba(0,0,0,0.55)',
        padding: bezel, boxSizing: 'border-box' }}>
        <ScreenSlot w={w} h={h} radius={46}>
          {children}
          {/* Dynamic island */}
          <div style={{ position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
            width: 108, height: 30, borderRadius: 999, background: '#000', zIndex: 40,
            pointerEvents: 'none' }} />
        </ScreenSlot>
      </div>
    </div>
  );
}

function DeviceFrame({ children }) {
  const { device } = useApp();
  if (device === 'laptop') return <LaptopFrame>{children}</LaptopFrame>;
  if (device === 'ipad') return <IpadFrame>{children}</IpadFrame>;
  return <IphoneFrame>{children}</IphoneFrame>;
}

// ─────────────────────────────────────────────────────────────
// Navigation
// ─────────────────────────────────────────────────────────────
const NAV_TABS = [
  { id: 'recipes', label: 'Recipes', icon: (p) => <Icon.bookmark {...p} /> },
  { id: 'cook', label: 'Cook', icon: (p) => <Icon.camera {...p} /> },
  { id: 'plan', label: 'Plan', icon: (p) => <Icon.list {...p} /> },
  { id: 'groceries', label: 'Groceries', icon: (p) => <Icon.upload {...p} /> },
];

function AvatarMenu() {
  const { logout, go, state } = useApp();
  const [open, setOpen] = useStateC(false);
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen((o) => !o)} style={{ background: 'transparent',
        border: 'none', cursor: 'pointer', padding: 0, display: 'flex' }}>
        <FAvatar size={34} />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 30 }} />
          <div style={{ position: 'absolute', top: 44, right: 0, zIndex: 31,
            minWidth: 200, padding: 8, borderRadius: 14,
            background: 'rgba(20,20,24,0.96)', backdropFilter: 'blur(20px)',
            border: '1px solid var(--hairline)', boxShadow: '0 24px 60px rgba(0,0,0,0.6)' }}>
            <div style={{ padding: '8px 12px 10px', borderBottom: '1px solid var(--hairline-2)' }}>
              <div style={{ fontFamily: 'Bricolage Grotesque', fontWeight: 600, fontSize: 14,
                color: 'var(--ink)' }}>Luis</div>
              <div style={{ fontFamily: 'Spectral', fontStyle: 'italic', fontSize: 12,
                color: 'var(--ink-3)' }}>{state.favourites.length} favourites</div>
            </div>
            {[
              { l: 'Settings', fn: () => { go('settings'); setOpen(false); } },
              { l: 'From other kitchens', fn: () => { go('shared'); setOpen(false); } },
              { l: 'Sign out', fn: () => { logout(); setOpen(false); } },
            ].map((m) => (
              <button key={m.l} onClick={m.fn} style={{ width: '100%', textAlign: 'left',
                background: 'transparent', border: 'none', cursor: 'pointer',
                padding: '9px 12px', borderRadius: 8, color: 'var(--ink-2)',
                fontFamily: 'Bricolage Grotesque', fontSize: 13, fontWeight: 500 }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.05)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>{m.l}</button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function AppHeader({ active, compact }) {
  const { setTab, go } = useApp();
  const pad = compact ? '16px 32px' : '20px 48px';
  return (
    <header style={{ display: 'flex', alignItems: 'center', gap: compact ? 22 : 32,
      padding: pad, borderBottom: '1px solid var(--hairline)', position: 'relative',
      zIndex: 5, flexShrink: 0 }}>
      <button onClick={() => setTab('recipes')} style={{ background: 'transparent',
        border: 'none', cursor: 'pointer', padding: 0 }}>
        <FWordmark size={compact ? 23 : 26} />
      </button>
      <nav style={{ display: 'flex', gap: 6, padding: 4, marginLeft: compact ? 8 : 16,
        background: 'rgba(255,255,255,0.04)', borderRadius: 999,
        border: '1px solid var(--hairline)' }}>
        {NAV_TABS.map((n) => {
          const isActive = active === n.id;
          return (
            <button key={n.id} onClick={() => setTab(n.id)} style={{
              fontFamily: 'Bricolage Grotesque', fontSize: compact ? 12 : 13, fontWeight: 500,
              padding: compact ? '7px 13px' : '8px 16px', borderRadius: 999, cursor: 'pointer',
              background: isActive ? 'linear-gradient(180deg, rgba(255,255,255,0.10), rgba(255,255,255,0.02))' : 'transparent',
              border: isActive ? '1px solid rgba(255,255,255,0.14)' : '1px solid transparent',
              color: isActive ? 'var(--ink)' : 'var(--ink-3)', whiteSpace: 'nowrap',
            }}>{n.label}</button>
          );
        })}
      </nav>
      <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 18 }}>
        <AvatarMenu />
      </div>
    </header>
  );
}

function MobileHeader({ title }) {
  const { setTab } = useApp();
  return (
    <header style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px',
      borderBottom: '1px solid var(--hairline)', position: 'relative', zIndex: 5,
      flexShrink: 0, paddingTop: 'var(--lc-mobile-top, 38px)' }}>
      <button onClick={() => setTab('recipes')} style={{ background: 'transparent',
        border: 'none', cursor: 'pointer', padding: 0 }}>
        <FWordmark size={22} />
      </button>
      <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 14 }}>
        <AvatarMenu />
      </div>
    </header>
  );
}

function MobileBottomNav({ active }) {
  const { setTab } = useApp();
  return (
    <nav style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
      padding: '8px 12px 22px', paddingBottom: 'calc(22px + var(--lc-mobile-bottom, 0px))',
      borderTop: '1px solid var(--hairline)',
      background: 'rgba(10,10,12,0.9)', backdropFilter: 'blur(20px)', flexShrink: 0, zIndex: 5 }}>
      {NAV_TABS.map((n) => {
        const isActive = active === n.id;
        return (
          <button key={n.id} onClick={() => setTab(n.id)} style={{ background: 'transparent',
            border: 'none', cursor: 'pointer', padding: '6px 4px', display: 'flex',
            flexDirection: 'column', alignItems: 'center', gap: 4,
            color: isActive ? 'var(--olive)' : 'var(--ink-3)' }}>
            {n.icon({ size: 20 })}
            <span style={{ fontFamily: 'Bricolage Grotesque', fontSize: 10, fontWeight: 600,
              letterSpacing: '0.04em' }}>{n.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ─────────────────────────────────────────────────────────────
// Shell — wraps a screen with chrome appropriate to the layout.
// chrome: 'full' (header + nav), 'none' (bare, e.g. cook mode / login)
// ─────────────────────────────────────────────────────────────
function Shell({ tab, chrome = 'full', children }) {
  const { layout, isLive } = useApp();
  // Prototype: 38px clears the fake iPhone dynamic island. Live: respect the real
  // device's safe-area inset (notch/status bar), falling back to a small inset.
  const frameStyle = { height: '100%', display: 'flex', flexDirection: 'column',
    overflow: 'hidden', position: 'relative',
    '--lc-mobile-top': isLive ? 'max(14px, env(safe-area-inset-top))' : '38px',
    '--lc-mobile-bottom': isLive ? 'max(0px, env(safe-area-inset-bottom))' : '0px' };
  if (chrome === 'none') {
    return <div id="lc-screen" className="lc lc-theme-f lc-paper" style={frameStyle}>{children}</div>;
  }
  if (layout === 'mobile') {
    return (
      <div id="lc-screen" className="lc lc-theme-f lc-paper" style={frameStyle}>
        <MobileHeader />
        <div data-app-scroll style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>{children}</div>
        <MobileBottomNav active={tab} />
      </div>
    );
  }
  const compact = layout === 'tablet';
  return (
    <div id="lc-screen" className="lc lc-theme-f lc-paper" style={frameStyle}>
      <AppHeader active={tab} compact={compact} />
      <div data-app-scroll style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>{children}</div>
    </div>
  );
}

Object.assign(window, {
  DeviceSwitcher, DeviceFrame, LaptopFrame, IpadFrame, IphoneFrame,
  AppHeader, MobileHeader, MobileBottomNav, Shell, NAV_TABS, DEVICE_ICONS,
});
