// Brisas do Lago — main app shell, routing, persona switching, tweaks

const { useState, useEffect } = React;

// Hash-based routing — públicos: '', '#minha-area' (cliente), '#admin' (backoffice oculto)
function readPersona() {
  const h = (typeof window !== 'undefined' ? window.location.hash : '').replace('#', '');
  if (h === 'admin') return 'backoffice';
  if (h === 'minha-area' || h === 'cliente') return 'cliente';
  return 'visitante';
}

function App() {
  const [persona, setPersonaState] = useState(readPersona);
  const [buyerStep, setBuyerStep] = useState('home');
  const [selectedLote, setSelectedLote] = useState(null);
  const [page, setPage] = useState(() => {
    const h = (typeof window !== 'undefined' ? window.location.hash : '').replace('#', '');
    return h === 'empreendimento' ? 'empreendimento' : 'home';
  });

  // sync persona ↔ url hash
  const setPersona = (p) => {
    setPersonaState(p);
    setPage('home');
    const h = p === 'backoffice' ? '#admin' : p === 'cliente' ? '#minha-area' : '';
    if (typeof window !== 'undefined') {
      if (h) window.location.hash = h;
      else if (window.location.hash) history.replaceState(null, '', window.location.pathname + window.location.search);
    }
  };

  const goToPage = (p) => {
    setPage(p);
    if (p === 'empreendimento') window.location.hash = 'empreendimento';
    else if (window.location.hash === '#empreendimento') {
      history.replaceState(null, '', window.location.pathname + window.location.search);
    }
  };

  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace('#', '');
      if (h === 'empreendimento') setPage('empreendimento');
      else {
        setPage('home');
        setPersonaState(readPersona());
      }
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Tweaks
  const [tweaks, setTweak] = window.useTweaks(/*EDITMODE-BEGIN*/{
    "mapStyle": "tecnico"
  }/*EDITMODE-END*/);

  // When persona changes, reset to home
  useEffect(() => {
    if (persona === 'visitante') setBuyerStep('home');
    if (persona === 'cliente') setSelectedLote(null);
  }, [persona]);

  const lote = selectedLote ? window.BL.LOTE_BY_NUM[selectedLote] : null;

  return (
    <>
      <Topbar persona={persona} setPersona={setPersona}
        onLogoClick={()=>{
          if (persona === 'visitante') { setBuyerStep('home'); goToPage('home'); }
        }}
        onNavEmpreendimento={()=>{ setPersona('visitante'); setBuyerStep('home'); goToPage('empreendimento'); }}
        onNavMapa={()=>{ setPersona('visitante'); setBuyerStep('map'); goToPage('home'); }}/>

      <main>
        {persona === 'visitante' && page === 'empreendimento' && (
          <window.EmpreendimentoPage onExplore={()=>{ setBuyerStep('map'); goToPage('home'); }}/>
        )}

        {persona === 'visitante' && page === 'home' && (
          <>
            {buyerStep === 'home' && (
              <>
                <BuyerHero onExplore={()=>setBuyerStep('map')}/>
                <BuyerMap onSelect={(n) => { setSelectedLote(n); setBuyerStep('detail'); }}/>
              </>
            )}
            {buyerStep === 'map' && (
              <BuyerMap onSelect={(n) => { setSelectedLote(n); setBuyerStep('detail'); }}/>
            )}
            {buyerStep === 'detail' && lote && (
              <BuyerLoteDetail lote={lote}
                onBack={()=>setBuyerStep('map')}
                onContinue={()=>setBuyerStep('reservar')}
                onSimular={()=>setBuyerStep('simulator')}/>
            )}
            {buyerStep === 'simulator' && lote && (
              <BuyerSimulador lote={lote}
                onBack={()=>setBuyerStep('detail')}
                onContinue={()=>setBuyerStep('reservar')}/>
            )}
            {buyerStep === 'reservar' && lote && (
              <BuyerReservar lote={lote}
                onBack={()=>setBuyerStep('detail')}
                onContinue={()=>setBuyerStep('cadastro')}/>
            )}
            {buyerStep === 'cadastro' && lote && (
              <BuyerCadastro lote={lote}
                onBack={()=>setBuyerStep('reservar')}
                onContinue={()=>setBuyerStep('contrato')}/>
            )}
            {buyerStep === 'contrato' && lote && (
              <BuyerContrato lote={lote}
                onBack={()=>setBuyerStep('cadastro')}
                onContinue={()=>setBuyerStep('pagamento')}/>
            )}
            {buyerStep === 'pagamento' && lote && (
              <BuyerPagamento lote={lote}
                onBack={()=>setBuyerStep('contrato')}
                onFinish={()=>{ setPersona('cliente'); }}/>
            )}
          </>
        )}

        {persona === 'cliente' && <ClientApp/>}

        {persona === 'backoffice' && <BackofficeApp/>}
      </main>

      <Footer/>

      {/* Demo persona switcher — discreet chip; in produção, remover este bloco */}
      <DemoBar persona={persona} setPersona={setPersona}/>

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Mapa">
          <window.TweakRadio
            label="Estilo"
            value={tweaks.mapStyle}
            onChange={(v)=>setTweak('mapStyle', v)}
            options={[
              {value:'tecnico', label:'Técnico'},
              {value:'esquematico', label:'Esquem.'},
              {value:'isometrico', label:'Isomé.'},
            ]}/>
        </window.TweakSection>
        <window.TweakSection label="Ir para">
          <window.TweakButton label="Backoffice" onClick={()=>setPersona('backoffice')}/>
          <window.TweakButton label="Área do cliente" onClick={()=>setPersona('cliente')}/>
          <window.TweakButton label="Fluxo de compra" onClick={()=>{ setPersona('visitante'); setBuyerStep('home'); }}/>
        </window.TweakSection>
      </window.TweaksPanel>
    </>
  );
}

function Topbar({persona, setPersona, onLogoClick, onNavEmpreendimento, onNavMapa}) {
  return (
    <header className="topbar">
      <div className="brand" onClick={onLogoClick} style={{cursor:'pointer'}}>
        <BrandMark size={42}/>
        <div style={{whiteSpace:'nowrap'}}>
          <div className="brand-name">Brisas do Lago</div>
          <div className="brand-sub">
            {persona === 'backoffice' ? 'Backoffice · admin' :
             persona === 'cliente' ? 'Minha área' :
             <>Lagoa do Cassó<br/>Primeira Cruz · MA</>}
          </div>
        </div>
      </div>

      {/* Nav central — varia por persona */}
      {persona === 'visitante' && (
        <nav style={{display:'flex', gap:24, alignItems:'center'}}>
          <a onClick={(e)=>{e.preventDefault(); onNavEmpreendimento?.();}} href="#empreendimento" style={{fontSize:13, fontWeight:600, color:'var(--ink-soft)', cursor:'pointer'}}>O empreendimento</a>
          <a onClick={(e)=>{e.preventDefault(); onNavMapa?.();}} href="#mapa" style={{fontSize:13, fontWeight:600, color:'var(--ink-soft)', cursor:'pointer'}}>Mapa de lotes</a>
          <a href="#" style={{fontSize:13, fontWeight:600, color:'var(--ink-soft)'}}>Galeria</a>
          <a href="#" style={{fontSize:13, fontWeight:600, color:'var(--ink-soft)'}}>Contato</a>
        </nav>
      )}

      <div className="topbar-right">
        {persona !== 'visitante' && (
          <button className="iconbtn" title="Notificações">
            <Icon name="bell" size={16}/>
            <span className="badge">3</span>
          </button>
        )}
        {persona === 'visitante' && (
          <>
            <button className="btn btn-sm btn-secondary" onClick={()=>setPersona('cliente')}>
              <Icon name="user" size={13}/> Entrar
            </button>
          </>
        )}
        {persona === 'cliente' && (
          <>
            <div style={{fontSize:12.5, color:'var(--ink-soft)', textAlign:'right'}}>
              <div style={{fontWeight:600, color:'var(--ink)'}}>Isabela Moraes</div>
              <div style={{fontSize:10.5}}>Lote 1 · Q.A</div>
            </div>
            <div className="avatar">IM</div>
            <button className="iconbtn" title="Sair" onClick={()=>setPersona('visitante')}>
              <Icon name="logout" size={15}/>
            </button>
          </>
        )}
        {persona === 'backoffice' && (
          <>
            <div style={{fontSize:12.5, color:'var(--ink-soft)', textAlign:'right'}}>
              <div style={{fontWeight:600, color:'var(--ink)'}}>Ana Mendes</div>
              <div style={{fontSize:10.5}}>Gerente · admin</div>
            </div>
            <div className="avatar" style={{background:'linear-gradient(135deg, var(--green), var(--green-deep))'}}>AM</div>
            <button className="iconbtn" title="Sair" onClick={()=>setPersona('visitante')}>
              <Icon name="logout" size={15}/>
            </button>
          </>
        )}
      </div>
    </header>
  );
}

function Footer() {
  return (
    <footer style={{
      padding:'40px 28px 30px', background:'var(--green-deep)', color:'var(--bg-card)',
      marginTop: 60
    }}>
      <div style={{maxWidth:1400, margin:'0 auto', display:'grid', gridTemplateColumns:'minmax(0, 1.4fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr)', gap:40}}>
        <div>
          <BrandMark size={42} dark/>
          <div className="display" style={{fontSize:26, fontWeight:500, marginTop:10}}>Brisas do Lago</div>
          <div style={{fontSize:12, color:'#D9C7A8', marginTop:6, letterSpacing:1, textTransform:'uppercase'}}>Loteamento Cassó SPE Ltda</div>
          <div style={{fontSize:13, marginTop:16, color:'#D9C7A8', lineHeight:1.6, maxWidth:340}}>
            Lagoa do Cassó · Primeira Cruz/MA · CEP 65190-000<br/>
            CNPJ 53.205.736/0001-62
          </div>
        </div>
        <div>
          <div className="eyebrow" style={{color:'#D9C7A8', marginBottom:14}}>◇ Empreendimento</div>
          <div style={{display:'flex', flexDirection:'column', gap:8, fontSize:13}}>
            {['Visão geral', 'Mapa de lotes', 'Galeria', 'Localização', 'Memorial descritivo'].map(l => <a key={l} href="#" style={{color:'var(--bg-card)', opacity:0.8}}>{l}</a>)}
          </div>
        </div>
        <div>
          <div className="eyebrow" style={{color:'#D9C7A8', marginBottom:14}}>◇ Compra</div>
          <div style={{display:'flex', flexDirection:'column', gap:8, fontSize:13}}>
            {['Simulador', 'Falar com corretor', 'Visita guiada', 'Documentação', 'FAQ'].map(l => <a key={l} href="#" style={{color:'var(--bg-card)', opacity:0.8}}>{l}</a>)}
          </div>
        </div>
        <div>
          <div className="eyebrow" style={{color:'#D9C7A8', marginBottom:14}}>◇ Contato</div>
          <div style={{display:'flex', flexDirection:'column', gap:8, fontSize:13}}>
            <a href="#" style={{color:'var(--bg-card)', opacity:0.8, display:'inline-flex', gap:8, alignItems:'center'}}><Icon name="phone" size={13}/> (98) 98765-4321</a>
            <a href="#" style={{color:'var(--bg-card)', opacity:0.8, display:'inline-flex', gap:8, alignItems:'center'}}><Icon name="mail" size={13}/> vendas@brisasdolago.com.br</a>
            <a href="#" style={{color:'var(--bg-card)', opacity:0.8, display:'inline-flex', gap:8, alignItems:'center'}}><Icon name="pin" size={13}/> Av. Fátima Costa, S/N</a>
          </div>
        </div>
      </div>
      <div style={{maxWidth:1400, margin:'30px auto 0', paddingTop:24, borderTop:'1px solid rgba(243,237,224,0.15)', display:'flex', justifyContent:'space-between', flexWrap:'wrap', gap:14, color:'#D9C7A8', fontSize:11.5}}>
        <div>© 2026 Brisas do Lago · Todos os direitos reservados</div>
        <div style={{display:'flex', gap:18}}>
          <a href="#" style={{color:'#D9C7A8'}}>Termos de uso</a>
          <a href="#" style={{color:'#D9C7A8'}}>Privacidade</a>
          <a href="#" style={{color:'#D9C7A8'}}>RI</a>
        </div>
      </div>
    </footer>
  );
}

// ─── Boot ─────────────────────────────────────────────
function DemoBar({persona, setPersona}) {
  const [collapsed, setCollapsed] = useState(false);
  const opts = [
    {id:'visitante', lbl:'Visitante', icon:'map'},
    {id:'cliente', lbl:'Cliente', icon:'user'},
    {id:'backoffice', lbl:'Admin', icon:'dashboard'},
  ];
  if (collapsed) {
    return (
      <button onClick={()=>setCollapsed(false)} style={{
        position:'fixed', bottom:16, left:16, zIndex:90,
        background:'rgba(26, 46, 32, 0.92)', color:'var(--bg-card)',
        border:'1px solid rgba(243,237,224,0.2)', borderRadius:100,
        padding:'7px 14px', fontSize:11, fontWeight:600, letterSpacing:0.5,
        boxShadow:'0 4px 16px rgba(0,0,0,0.15)', cursor:'pointer',
        display:'inline-flex', alignItems:'center', gap:6
      }}>
        <Icon name="eye" size={12}/> Modo demo
      </button>
    );
  }
  return (
    <div style={{
      position:'fixed', bottom:16, left:16, zIndex:90,
      background:'rgba(26, 46, 32, 0.92)', color:'var(--bg-card)',
      border:'1px solid rgba(243,237,224,0.2)', borderRadius:100,
      padding:4, boxShadow:'0 4px 16px rgba(0,0,0,0.18)',
      display:'flex', alignItems:'center', gap:2, backdropFilter:'blur(10px)',
      fontSize:11
    }}>
      <div style={{padding:'0 10px 0 12px', fontSize:10, fontWeight:700, letterSpacing:1, color:'#D9C7A8', textTransform:'uppercase', whiteSpace:'nowrap'}}>
        Demo
      </div>
      {opts.map(o => (
        <button key={o.id} onClick={()=>setPersona(o.id)} style={{
          padding:'6px 12px', borderRadius:100,
          fontSize:11, fontWeight:600,
          background: persona === o.id ? 'var(--terra)' : 'transparent',
          color: persona === o.id ? 'var(--bg-card)' : '#D9C7A8',
          display:'inline-flex', alignItems:'center', gap:5, cursor:'pointer',
          whiteSpace:'nowrap'
        }}>
          <Icon name={o.icon} size={11}/> {o.lbl}
        </button>
      ))}
      <button onClick={()=>setCollapsed(true)} title="Esconder" style={{
        padding:'6px 8px', color:'#D9C7A8', cursor:'pointer'
      }}><Icon name="x" size={11}/></button>
    </div>
  );
}

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