// ============================================================
// APP — Convés root, navigation, tab bar, device frame
// ============================================================
const { useState: useAppState, useEffect: useAppEffect, useRef: useAppRef } = React;

const OWNER_TABS = [
  { key:'home',     label:'Início',       icon:'Home' },
  { key:'boats',    label:'Embarcações',  icon:'Anchor' },
  { key:'messages', label:'Mensagens',    icon:'MessageSquare', badge:3 },
  { key:'logbook',  label:'Logbook',      icon:'BookOpen' },
  { key:'profile',  label:'Perfil',       icon:'User' },
];
const PRO_TABS = [
  { key:'pro-home',    label:'Início',     icon:'Home' },
  { key:'pro-orders',  label:'OS',         icon:'ClipboardList', badge:3 },
  { key:'messages',    label:'Mensagens',  icon:'MessageSquare', badge:5 },
  { key:'pro-agenda',  label:'Agenda',     icon:'Calendar' },
  { key:'profile',     label:'Perfil',     icon:'User' },
];

// Routes where the tab bar is hidden (full-screen flows)
const HIDE_TAB_BAR = new Set([
  'onboarding','login','quote-new','quotes','pro-detail','order-detail',
  'chat','review','boat-new','concierge','notif','pro-quote-new',
  'pro-onboarding','admin','demo-intro',
]);

// Detect demo mode from URL query string
function isDemoMode() {
  try {
    return new URLSearchParams(window.location.search).get('demo') === 'true';
  } catch (e) { return false; }
}

// Map route -> which tab (for tab-bar highlight on persistent screens)
const ROUTE_TAB = {
  home:'home', boats:'boats', messages:'messages', logbook:'logbook', profile:'profile',
  pros:'home',
  'pro-home':'pro-home', 'pro-orders':'pro-orders', 'pro-agenda':'pro-agenda',
};

function App() {
  const [route, setRoute] = useAppState(isDemoMode() ? 'demo-intro' : 'home');
  const [history, setHistory] = useAppState([]);
  const [mode, setMode] = useAppState('owner'); // 'owner' | 'pro'
  const [dark, setDark] = useAppState(false);
  const scrollRef = useAppRef(null);

  function go(next) {
    if (next === route) return;
    setHistory(h => [...h, route]);
    setRoute(next);
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }
  function back() {
    setHistory(h => {
      const last = h[h.length-1] || 'home';
      setRoute(last);
      return h.slice(0,-1);
    });
  }

  // expose for debug
  useAppEffect(()=>{ window.__go = go; }, [route]);

  const tabs = mode === 'owner' ? OWNER_TABS : PRO_TABS;
  const activeTab = ROUTE_TAB[route] || (mode==='owner' ? 'home' : 'pro-home');
  const showTabBar = !HIDE_TAB_BAR.has(route);

  // Screen renderer
  function renderScreen() {
    const ctx = { go, back, mode, setMode, dark, setDark };
    switch (route) {
      // Demo
      case 'demo-intro':    return <DemoIntro {...ctx}/>;
      // Owner
      case 'onboarding':    return <Onboarding {...ctx}/>;
      case 'login':         return <LoginScreen {...ctx}/>;
      case 'home':          return <HomeOwner {...ctx}/>;
      case 'boats':         return <BoatsList {...ctx}/>;
      case 'boat-new':      return <BoatNew {...ctx}/>;
      case 'quote-new':     return <QuoteNew {...ctx}/>;
      case 'quotes':        return <QuotesScreen {...ctx}/>;
      case 'pro-detail':    return <ProDetail {...ctx}/>;
      case 'order-detail':  return <OrderDetail {...ctx}/>;
      case 'orders':        return <OrdersList {...ctx}/>;
      case 'chat':          return <ChatScreen {...ctx}/>;
      case 'review':        return <ReviewScreen {...ctx}/>;
      case 'logbook':       return <LogbookScreen {...ctx}/>;
      case 'messages':      return <MessagesList {...ctx}/>;
      case 'pros':          return <ProsList {...ctx}/>;
      case 'notif':         return <NotifScreen {...ctx}/>;
      case 'concierge':     return <ConciergeScreen {...ctx}/>;
      // Pro
      case 'pro-home':      return <HomePro {...ctx}/>;
      case 'pro-orders':    return <ProOrdersScreen {...ctx}/>;
      case 'pro-quote-new': return <ProQuoteNew {...ctx}/>;
      case 'pro-agenda':    return <ProAgendaScreen {...ctx}/>;
      case 'pro-onboarding':return <ProOnboarding {...ctx}/>;
      // Admin
      case 'admin':         return <AdminScreen {...ctx}/>;
      // Shared
      case 'profile':       return <ProfileScreen {...ctx}/>;
      default:              return <HomeOwner {...ctx}/>;
    }
  }

  // When switching mode, jump to that mode's home
  useAppEffect(()=>{
    if (mode==='owner' && route.startsWith('pro')) go('home');
    if (mode==='pro' && !route.startsWith('pro') && route!=='messages' && route!=='profile') go('pro-home');
    // eslint-disable-next-line
  }, [mode]);

  return (
    <div style={{ position:'relative' }}>
      <DeviceShell dark={dark}>
        <div ref={scrollRef} className="scroll-clean" style={{
          flex:1, overflowY:'auto', overflowX:'hidden',
          paddingBottom: showTabBar ? 86 : 0,
          background: dark ? 'var(--bg-dark)' : 'var(--bg)',
          color: dark ? '#fff' : 'var(--text)',
          position:'relative', height:'100%',
        }}>
          {renderScreen()}
        </div>
        {showTabBar && (
          <TabBar
            active={activeTab}
            onChange={k=>go(k)}
            items={tabs}
          />
        )}
      </DeviceShell>

      {/* Quick mode toggle floating helper for prototype convenience */}
      <ModeFab mode={mode} setMode={setMode} route={route} go={go}/>
    </div>
  );
}

// ---------- Device shell ----------
function DeviceShell({ children, dark }) {
  const W = 390, H = 844;
  return (
    <div style={{
      width:W, height:H, borderRadius:48, overflow:'hidden', position:'relative',
      background: dark ? '#000' : '#FAFAFA',
      boxShadow:'0 40px 80px rgba(15,20,25,0.18), 0 0 0 1px rgba(15,20,25,0.10), 0 0 0 8px #15171C, 0 0 0 9px rgba(255,255,255,0.06)',
      fontFamily:"'Inter', system-ui, sans-serif",
    }}>
      {/* dynamic island */}
      <div style={{
        position:'absolute', top:11, left:'50%', transform:'translateX(-50%)',
        width:120, height:34, borderRadius:24, background:'#000', zIndex:60,
      }}/>
      {/* status bar */}
      <div style={{
        position:'absolute', top:0, left:0, right:0, height:54, zIndex:50,
        display:'flex', alignItems:'center', justifyContent:'space-between',
        padding:'18px 28px 0', color: dark ? '#fff' : '#000',
        pointerEvents:'none',
      }}>
        <span style={{fontWeight:600, fontSize:15, letterSpacing:-.2}}>9:41</span>
        <div style={{display:'flex', alignItems:'center', gap:6}}>
          <svg width="17" height="11" viewBox="0 0 17 11"><rect x="0" y="7" width="2.6" height="4" rx="0.6" fill="currentColor"/><rect x="4" y="5" width="2.6" height="6" rx="0.6" fill="currentColor"/><rect x="8" y="3" width="2.6" height="8" rx="0.6" fill="currentColor"/><rect x="12" y="1" width="2.6" height="10" rx="0.6" fill="currentColor"/></svg>
          <svg width="14" height="11" viewBox="0 0 14 11"><path d="M7 3a6 6 0 014.2 1.8l1-1A7.5 7.5 0 007 1.5 7.5 7.5 0 001.8 3.8l1 1A6 6 0 017 3z" fill="currentColor"/><path d="M7 6a3 3 0 012.1 1l1-1A4.5 4.5 0 007 4.5 4.5 4.5 0 003.9 6l1 1A3 3 0 017 6z" fill="currentColor"/><circle cx="7" cy="9.5" r="1.2" fill="currentColor"/></svg>
          <svg width="24" height="11" viewBox="0 0 24 11"><rect x="0.5" y="0.5" width="20" height="10" rx="2.6" stroke="currentColor" strokeOpacity=".35" fill="none"/><rect x="2" y="2" width="17" height="7" rx="1.4" fill="currentColor"/><path d="M21.5 4v3c.7-.2 1.2-.9 1.2-1.5s-.5-1.3-1.2-1.5z" fill="currentColor" fillOpacity=".5"/></svg>
        </div>
      </div>
      {/* status bar safe area + content */}
      <div style={{ height:'100%', display:'flex', flexDirection:'column', paddingTop:54 }}>
        {children}
      </div>
      {/* home indicator */}
      <div style={{
        position:'absolute', bottom:8, left:0, right:0, display:'flex', justifyContent:'center', zIndex:80, pointerEvents:'none',
      }}>
        <div style={{ width:134, height:5, borderRadius:6, background: dark ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.25)' }}/>
      </div>
    </div>
  );
}

// ---------- Floating Mode FAB (prototype helper, not part of product) ----------
function ModeFab({ mode, setMode, route, go }) {
  const [open, setOpen] = useAppState(false);
  return (
    <div style={{
      position:'absolute', top:0, left:'100%', marginLeft:24,
      display:'flex', flexDirection:'column', gap:10, alignItems:'flex-start', minWidth:230,
    }}>
      <div style={{
        background:'#15171C', color:'#fff', borderRadius:14, padding:'14px 16px',
        fontSize:12.5, lineHeight:1.5, maxWidth:260,
        boxShadow:'0 8px 24px rgba(0,0,0,0.18)',
      }}>
        <div style={{display:'flex', alignItems:'center', gap:6, marginBottom:8}}>
          <div style={{width:22, height:22, borderRadius:7, background:'var(--primary)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700}}>C</div>
          <span style={{fontWeight:700, letterSpacing:-.2}}>Convés</span>
          <span style={{marginLeft:'auto', fontSize:10, color:'rgba(255,255,255,0.5)'}} className="mono">v1.4 · protótipo</span>
        </div>
        <p style={{margin:'0 0 10px', color:'rgba(255,255,255,0.7)'}}>
          Marketplace náutico curado — protótipo navegável dos fluxos do proprietário e do prestador.
        </p>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, background:'rgba(255,255,255,0.08)', padding:4, borderRadius:10}}>
          <button onClick={()=>setMode('owner')} style={{
            background: mode==='owner' ? 'var(--primary)' : 'transparent',
            color:'#fff', border:'none', borderRadius:7, padding:'7px 8px',
            fontSize:12, fontWeight: mode==='owner'?600:500, cursor:'pointer',
            display:'inline-flex', alignItems:'center', justifyContent:'center', gap:5,
          }}><Icon name="Anchor" size={13} strokeWidth={2} color="#fff"/> Proprietário</button>
          <button onClick={()=>setMode('pro')} style={{
            background: mode==='pro' ? 'var(--primary)' : 'transparent',
            color:'#fff', border:'none', borderRadius:7, padding:'7px 8px',
            fontSize:12, fontWeight: mode==='pro'?600:500, cursor:'pointer',
            display:'inline-flex', alignItems:'center', justifyContent:'center', gap:5,
          }}><Icon name="Wrench" size={13} strokeWidth={2} color="#fff"/> Prestador</button>
        </div>
      </div>

      <div style={{
        background:'#15171C', color:'rgba(255,255,255,0.9)', borderRadius:14, padding:'14px 16px',
        fontSize:12, lineHeight:1.55, maxWidth:260,
        boxShadow:'0 8px 24px rgba(0,0,0,0.18)',
      }}>
        <div style={{display:'flex', alignItems:'center', gap:6, marginBottom:8}}>
          <Icon name="Compass" size={13} color="#C5A572" strokeWidth={2}/>
          <span style={{fontWeight:700, color:'#fff', letterSpacing:-.2}}>Tour rápido</span>
        </div>
        <ol style={{margin:0, paddingLeft:18, color:'rgba(255,255,255,0.75)'}}>
          <li style={{marginBottom:4}}><a onClick={()=>go('login')} style={linkStyle}>P2 Login / OTP</a></li>
          <li style={{marginBottom:4}}><a onClick={()=>go('onboarding')} style={linkStyle}>P1 Onboarding</a> → <a onClick={()=>go('home')} style={linkStyle}>P3 Home</a></li>
          <li style={{marginBottom:4}}><a onClick={()=>go('quote-new')} style={linkStyle}>P6 Orçamento</a> → <a onClick={()=>go('quotes')} style={linkStyle}>P7 Cotações</a></li>
          <li style={{marginBottom:4}}><a onClick={()=>go('pro-detail')} style={linkStyle}>P8 Prestador</a> → <a onClick={()=>go('order-detail')} style={linkStyle}>P9 Acompanhar</a></li>
          <li style={{marginBottom:4}}><a onClick={()=>go('chat')} style={linkStyle}>P10 Chat</a> → <a onClick={()=>go('review')} style={linkStyle}>P12 Avaliação</a></li>
          <li style={{marginBottom:4}}><a onClick={()=>go('logbook')} style={linkStyle}>P11 Logbook</a></li>
          <li style={{marginBottom:4}}><a onClick={()=>{setMode('pro'); go('pro-onboarding');}} style={linkStyle}>M1 Onboarding prestador</a></li>
          <li style={{marginBottom:4}}><a onClick={()=>{setMode('pro'); go('pro-home');}} style={linkStyle}>M2 Home prestador</a></li>
          <li><a onClick={()=>go('admin')} style={linkStyle}>Admin · Curadoria</a></li>
        </ol>
      </div>

      <div style={{
        background:'rgba(255,255,255,0.7)', color:'var(--text-muted)', borderRadius:12, padding:'10px 12px',
        fontSize:11, lineHeight:1.5, maxWidth:260, border:'1px solid rgba(0,0,0,0.06)',
      }} className="mono">
        Tela atual: <span style={{color:'var(--text)', fontWeight:600}}>{route}</span>
      </div>
    </div>
  );
}
const linkStyle = { color:'#C5A572', textDecoration:'none', cursor:'pointer', fontWeight:600 };

// ---------- Orders list (owner view) ----------
function OrdersList({ go }) {
  return (
    <div className="screen-enter" style={{paddingBottom:24}}>
      <ScreenHeader title="Ordens de serviço" large onBack={()=>go('home')}/>
      <div style={{padding:'4px 16px 0', display:'flex', flexDirection:'column', gap:10}}>
        {ORDERS.map(o=>{
          const pro = PROS.find(p=>p.id===o.proId);
          const boat = BOATS.find(b=>b.id===o.boatId);
          return (
            <button key={o.id} onClick={()=>go('order-detail')} className="ripple" style={{
              width:'100%', textAlign:'left', background:'var(--surface)', border:'1px solid var(--border)',
              borderRadius:16, padding:14, cursor:'pointer',
            }}>
              <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10}}>
                <OrderStatusPill status={o.status}/>
                <span className="mono" style={{fontSize:11, color:'var(--text-subtle)'}}>{o.id}</span>
              </div>
              <div style={{fontSize:14.5, fontWeight:600, color:'var(--text)'}}>{o.title}</div>
              <div style={{fontSize:12, color:'var(--text-muted)', marginTop:2}}>{boat.name} · {pro.short}</div>
              <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:10}}>
                <span style={{fontSize:12, color:'var(--text-subtle)'}}>
                  {o.scheduledFor ? 'Agendado para ' + o.scheduledFor : 'Aguardando agendamento'}
                </span>
                <span className="mono" style={{fontSize:13, fontWeight:600, color:'var(--text)'}}>
                  {o.total > 0 ? brl(o.total) : '—'}
                </span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ---------- Pro Agenda screen ----------
function ProAgendaScreen({ go }) {
  const days = ['Seg','Ter','Qua','Qui','Sex','Sáb','Dom'];
  const dates = [12,13,14,15,16,17,18];
  const activeIdx = 4; // Friday
  const slots = [
    { time:'08:00', service:null },
    { time:'09:00', service:{ title:'Troca de óleo · Bonança', client:'Pedro M.', os:'OS-2826', tone:'#1F3864' }, span:2 },
    { time:'10:00', service:null },
    { time:'11:00', service:null },
    { time:'12:00', service:null },
    { time:'13:00', service:null },
    { time:'14:00', service:{ title:'Diagnóstico de partida', client:'Eduardo S.', os:'OS-2828', tone:'#C5A572' }, span:1 },
    { time:'15:00', service:null },
    { time:'16:00', service:null },
    { time:'17:00', service:null },
  ];
  return (
    <div className="screen-enter" style={{paddingBottom:24}}>
      <ScreenHeader title="Agenda" large
        right={<button className="ripple" style={{
          width:36, height:36, borderRadius:36, border:'1px solid var(--border)',
          background:'var(--surface)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
        }}><Icon name="Plus" size={18} strokeWidth={2}/></button>}/>
      <div style={{padding:'8px 16px 0'}}>
        <div style={{fontSize:14, color:'var(--text-muted)', marginBottom:10}}>Maio · 2026</div>
        <div style={{display:'flex', gap:6, marginBottom:18}}>
          {days.map((d,i)=>{
            const on = i===activeIdx;
            return (
              <div key={d} style={{
                flex:1, textAlign:'center', padding:'8px 0', borderRadius:10,
                background: on ? 'var(--primary)' : 'var(--surface)',
                border:'1px solid ' + (on ? 'var(--primary)' : 'var(--border)'),
                color: on ? '#fff' : 'var(--text)',
              }}>
                <div style={{fontSize:10.5, color: on ? 'rgba(255,255,255,0.7)' : 'var(--text-subtle)', textTransform:'uppercase', letterSpacing:.5}}>{d}</div>
                <div className="mono" style={{fontSize:16, fontWeight:700, marginTop:2}}>{dates[i]}</div>
              </div>
            );
          })}
        </div>

        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {slots.map(s=>(
            <div key={s.time} style={{display:'flex', alignItems:'stretch', gap:10, minHeight:s.service ? 64 : 36}}>
              <div className="mono" style={{width:46, fontSize:11.5, color:'var(--text-subtle)', paddingTop:2}}>{s.time}</div>
              <div style={{flex:1, borderTop:'1px solid var(--border)', position:'relative', paddingTop:6}}>
                {s.service && (
                  <div style={{
                    background:'var(--surface)', border:'1px solid var(--border)',
                    borderLeft: '3px solid ' + s.service.tone,
                    borderRadius:10, padding:'10px 12px',
                  }}>
                    <div style={{fontSize:13.5, fontWeight:600, color:'var(--text)'}}>{s.service.title}</div>
                    <div style={{fontSize:12, color:'var(--text-muted)', marginTop:2}}>{s.service.client} · {s.service.os}</div>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OrdersList, ProAgendaScreen });

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