// Main app — DashM Advogados interactive prototype
// Hostbar with platform switcher (Mobile/Desktop) + theme toggle.
// Single device frame with real navigation between screens.

const ThemeCtx = React.createContext(window.T.dark);
window.ThemeCtx = ThemeCtx;

// Mobile screen registry
const MOBILE_SCREENS = {
  home:           { Comp: () => <MDashboard/>,        tab: 'home' },
  crm:            { Comp: () => <MCRM/>,              tab: 'crm' },
  proc:           { Comp: () => <MProcessos/>,        tab: 'proc' },
  'processo-det': { Comp: () => <MProcessoDetalhe/>,  tab: 'proc' },
  pet:            { Comp: () => <MEditorPeticao/>,    tab: 'pet' },
  editor:         { Comp: () => <MEditorPeticao/>,    tab: 'pet' },
  acervo:         { Comp: () => <MAcervoIA/>,         tab: 'pet' },
  mais:           { Comp: () => <MMais/>,             tab: 'mais' },
  contratos:      { Comp: () => <MContratos/>,        tab: 'mais' },
  biblio:         { Comp: () => <MBiblioteca/>,       tab: 'mais' },
  financeiro:     { Comp: () => <MFinanceiro/>,       tab: 'mais' },
  invest:         { Comp: () => <MInvestimentos/>,    tab: 'mais' },
  estudo:         { Comp: () => <MEstudo/>,           tab: 'mais' },
};

// Desktop screen registry
function DPlaceholder({ active, title, sub, icon }) {
  const t = React.useContext(ThemeCtx);
  return <DesktopShell active={active}>
    <div style={{ padding: 22, height: '100%', boxSizing: 'border-box', display: 'flex', flexDirection: 'column' }}>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 11, color: t.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>{sub}</div>
        <h1 style={{ fontFamily: '"Playfair Display", serif', fontSize: 28, fontWeight: 600, margin: '4px 0 0', color: t.text }}>{title}</h1>
      </div>
      <div style={{
        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: t.surface, border: `1px dashed ${t.border}`, borderRadius: 14,
      }}>
        <div style={{ textAlign: 'center', maxWidth: 360 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 14, background: t.chipBg, color: t.chipText,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14,
          }}><Icon name={icon} size={26}/></div>
          <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 18, fontWeight: 600, color: t.text, marginBottom: 6 }}>Tela desktop em construção</div>
          <div style={{ fontSize: 12.5, color: t.subtext, lineHeight: 1.55, marginBottom: 14 }}>
            Esta área já existe no mobile. A versão ampla para uso de mesa segue o mesmo sistema visual e regras de navegação.
          </div>
          <Btn size="md" variant="ghost">Ver no mobile →</Btn>
        </div>
      </div>
    </div>
  </DesktopShell>;
}

const DESKTOP_SCREENS = {
  home: { Comp: () => <DDashboard/> },
  crm:  { Comp: () => <DCRM/> },
  pet:  { Comp: () => <DEditor/> },
  acv:  { Comp: () => <DAcervo/> },
  proc: { Comp: () => <DPlaceholder active="proc" sub="Jurídico" title="Processos" icon="gavel"/> },
  cont: { Comp: () => <DPlaceholder active="cont" sub="Jurídico" title="Contratos" icon="doc"/> },
  bib:  { Comp: () => <DPlaceholder active="bib"  sub="Jurídico" title="Biblioteca · Autores" icon="book"/> },
  fin:  { Comp: () => <DPlaceholder active="fin"  sub="Patrimônio" title="Financeiro" icon="wallet"/> },
  inv:  { Comp: () => <DPlaceholder active="inv"  sub="Patrimônio" title="Investimentos" icon="trend"/> },
  fis:  { Comp: () => <DPlaceholder active="fis"  sub="Patrimônio" title="Fiscal" icon="shield"/> },
  agd:  { Comp: () => <DPlaceholder active="agd"  sub="Pessoal" title="Agenda" icon="calendar"/> },
  est:  { Comp: () => <DPlaceholder active="est"  sub="Pessoal" title="Estudo" icon="feather"/> },
};

function Hostbar({ mode, setMode, platform, setPlatform }) {
  const isDark = mode === 'dark';
  const seg = (val, current, onClick, children) => (
    <button onClick={onClick} style={{
      border: 'none', background: val === current ? '#fff' : 'transparent',
      color: val === current ? '#2a1d12' : '#6e5a44', cursor: 'pointer',
      borderRadius: 999, padding: '4px 11px', fontSize: 11, fontWeight: 600,
      fontFamily: 'Inter, system-ui', display: 'flex', alignItems: 'center', gap: 5,
      boxShadow: val === current ? '0 1px 2px rgba(0,0,0,0.1)' : 'none',
    }}>{children}</button>
  );
  return <div style={{
    position: 'fixed', top: 16, left: '50%', transform: 'translateX(-50%)', zIndex: 1000,
    display: 'flex', alignItems: 'center', gap: 12,
    background: 'rgba(255,251,243,0.92)', backdropFilter: 'blur(14px)',
    border: '1px solid rgba(60,30,10,0.10)', borderRadius: 999,
    padding: '6px 8px 6px 14px',
    boxShadow: '0 6px 20px rgba(60,30,10,0.10), 0 1px 2px rgba(60,30,10,0.04)',
    fontFamily: 'Inter, system-ui',
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{
        width: 22, height: 22, borderRadius: 6, background: '#8b4513', color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: '"Playfair Display", serif', fontWeight: 700, fontSize: 12,
      }}>D</div>
      <div style={{ fontFamily: '"Playfair Display", serif', fontWeight: 700, fontSize: 14, color: '#2a1d12', letterSpacing: -0.2 }}>DashM <span style={{ fontWeight: 500, color: '#6e5a44' }}>Advogados</span></div>
    </div>
    <div style={{ width: 1, height: 18, background: 'rgba(60,30,10,0.12)' }}/>
    <div style={{ display: 'flex', background: 'rgba(60,30,10,0.06)', borderRadius: 999, padding: 2 }}>
      {seg('mobile', platform, () => setPlatform('mobile'), <><MobileIcon/> Mobile</>)}
      {seg('desktop', platform, () => setPlatform('desktop'), <><DesktopIcon/> Desktop</>)}
    </div>
    <div style={{ width: 1, height: 18, background: 'rgba(60,30,10,0.12)' }}/>
    <div style={{ display: 'flex', background: 'rgba(60,30,10,0.06)', borderRadius: 999, padding: 2 }}>
      {seg('light', mode, () => setMode('light'), <><Icon name="sun" size={12}/> Light</>)}
      {seg('dark',  mode, () => setMode('dark'),  <><Icon name="moon" size={12}/> Dark</>)}
    </div>
  </div>;
}

const MobileIcon = () => <svg width="11" height="14" viewBox="0 0 11 14" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="0.8" y="0.8" width="9.4" height="12.4" rx="1.6"/><circle cx="5.5" cy="11.5" r="0.4" fill="currentColor"/></svg>;
const DesktopIcon = () => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="0.8" y="1.2" width="12.4" height="8.5" rx="1.2"/><path d="M4 12.5h6M7 9.7v2.8"/></svg>;

// Inner app that uses the nav context — renders the current screen.
function AppInner({ platform }) {
  const nav = useNav();
  const t = React.useContext(ThemeCtx);

  if (platform === 'mobile') {
    const reg = MOBILE_SCREENS[nav.screen] || MOBILE_SCREENS.home;
    const { Comp, tab } = reg;
    return <IOSDevice width={402} height={874} dark={t === window.T.dark}>
      <div style={{ background: t.bg, minHeight: '100%', paddingTop: 50, boxSizing: 'border-box' }}>
        <ActiveTabCtx.Provider value={tab}><Comp/></ActiveTabCtx.Provider>
      </div>
    </IOSDevice>;
  }

  const reg = DESKTOP_SCREENS[nav.screen] || DESKTOP_SCREENS.home;
  const { Comp } = reg;
  return <ChromeWindow width={1260} height={780} url={`app.dashm.adv.br/${nav.screen}`} tabs={[{ title: 'DashM Advogados', active: true }]}>
    <Comp/>
  </ChromeWindow>;
}

const ActiveTabCtx = React.createContext('home');
window.ActiveTabCtx = ActiveTabCtx;

function App() {
  const [mode, setMode] = React.useState(() => {
    try { return localStorage.getItem('dashm-theme') || 'dark'; } catch { return 'dark'; }
  });
  const [platform, setPlatform] = React.useState(() => {
    try { return localStorage.getItem('dashm-platform') || 'mobile'; } catch { return 'mobile'; }
  });
  React.useEffect(() => { try { localStorage.setItem('dashm-theme', mode); } catch {} }, [mode]);
  React.useEffect(() => { try { localStorage.setItem('dashm-platform', platform); } catch {} }, [platform]);

  const t = window.T[mode];
  const initial = platform === 'mobile' ? 'home' : 'home';

  return <ThemeCtx.Provider value={t}>
    <Hostbar mode={mode} setMode={setMode} platform={platform} setPlatform={setPlatform}/>

    <NavProvider key={platform} initial={initial}>
      <div style={{
        minHeight: '100vh', width: '100%',
        background: `radial-gradient(circle at 50% 0%, ${mode === 'dark' ? '#3a2a1f' : '#f0e0c4'} 0%, ${mode === 'dark' ? '#1a120c' : '#f5ede1'} 60%)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '90px 24px 36px', boxSizing: 'border-box',
        overflow: 'auto',
      }}>
        <AppInner platform={platform}/>
      </div>
    </NavProvider>
  </ThemeCtx.Provider>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
