// SGAB v2 — Agenda Mensal Visual
const { useState, useMemo } = React;

const DIAS_SEMANA = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
const MESES = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];

function Agenda({ user, toast }) {
  const isAdmin = user.perfil === 'administrador';
  const hoje = new Date();
  const [ano, setAno]   = useState(hoje.getFullYear());
  const [mes, setMes]   = useState(hoje.getMonth());
  const [db, setDb]     = useState(() => SGAB.getDB());
  const [modal, setModal]   = useState(false);
  const [selDia, setSelDia] = useState(null);
  const [editando, setEditando] = useState(null);
  const [form, setForm] = useState({});
  const { fmt } = SGAB;

  function reload() { setDb(SGAB.getDB()); }

  // Dias do mês
  const diasDoMes = useMemo(() => {
    const primeiroDia = new Date(ano, mes, 1).getDay();
    const totalDias   = new Date(ano, mes + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < primeiroDia; i++) cells.push(null);
    for (let d = 1; d <= totalDias; d++) cells.push(d);
    // pad to complete last row
    while (cells.length % 7 !== 0) cells.push(null);
    return cells;
  }, [ano, mes]);

  function dataStr(d) {
    return `${ano}-${String(mes+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
  }

  function entradasDia(d) {
    if (!d) return [];
    return db.agenda.filter(e => e.data === dataStr(d));
  }

  // Totais do mês
  const totais = useMemo(() => {
    const prefix = `${ano}-${String(mes+1).padStart(2,'0')}`;
    const entries = db.agenda.filter(e => e.data.startsWith(prefix));
    return {
      creditos: entries.filter(e=>e.tipo==='credito').reduce((s,e)=>s+(e.valor||0),0),
      debitos:  entries.filter(e=>e.tipo==='debito').reduce((s,e)=>s+(e.valor||0),0),
    };
  }, [db, ano, mes]);

  function navMes(dir) {
    let nm = mes + dir, na = ano;
    if (nm < 0) { nm = 11; na--; }
    if (nm > 11) { nm = 0; na++; }
    setMes(nm); setAno(na);
  }

  function openModal(dia, entrada=null) {
    setSelDia(dia);
    if (entrada) {
      setEditando(entrada);
      setForm({ data:entrada.data, tipo:entrada.tipo, desc:entrada.desc, valor:entrada.valor||'', clienteId:entrada.clienteId||'', status:entrada.status, riscado:entrada.riscado });
    } else {
      setEditando(null);
      const dataInicial = dia ? dataStr(dia) : fmt.today();
      setForm({ data:dataInicial, tipo:'servico', desc:'', valor:'', clienteId:'', status:'agendado', riscado:false });
    }
    setModal(true);
  }

  function salvar() {
    if (!form.desc || !form.desc.trim()) { toast('Informe a descrição.','error'); return; }
    if (!form.data) { toast('Informe a data.','error'); return; }
    const newDb = SGAB.getDB();
    const payload = { ...form, valor: form.valor?+form.valor:null, clienteId:form.clienteId?+form.clienteId:null };
    if (editando) {
      const idx = newDb.agenda.findIndex(e=>e.id===editando.id);
      if (idx>=0) newDb.agenda[idx] = { ...newDb.agenda[idx], ...payload };
    } else {
      const id = SGAB.nxtId(newDb,'agenda');
      newDb.agenda.push({ id, ...payload });
    }
    SGAB.saveDB(newDb); reload(); setModal(false);
    // Reposicionar calendário no mês da data salva
    const [yy, mm] = form.data.split('-');
    setAno(+yy); setMes(+mm - 1);
    toast(editando?'Entrada atualizada!':'Entrada adicionada!');
  }

  function excluir(entrada) {
    if (!confirm('Excluir esta entrada?')) return;
    const newDb = SGAB.getDB();
    newDb.agenda = newDb.agenda.filter(e=>e.id!==entrada.id);
    SGAB.saveDB(newDb); reload();
    toast('Entrada removida.','info');
  }

  function toggleRiscado(entrada) {
    const newDb = SGAB.getDB();
    const idx = newDb.agenda.findIndex(e=>e.id===entrada.id);
    if (idx>=0) newDb.agenda[idx].riscado = !newDb.agenda[idx].riscado;
    SGAB.saveDB(newDb); reload();
  }

  function toggleFinalizado(entrada) {
    const newDb = SGAB.getDB();
    const idx = newDb.agenda.findIndex(e=>e.id===entrada.id);
    if (idx>=0) newDb.agenda[idx].status = newDb.agenda[idx].status==='finalizado'?'agendado':'finalizado';
    SGAB.saveDB(newDb); reload();
  }

  // Cell entry style
  function entryStyle(e) {
    const base = { fontSize:11, padding:'2px 6px', borderRadius:4, marginBottom:2, cursor:'pointer',
      textDecoration:e.riscado?'line-through':'none', display:'flex', alignItems:'center', gap:4,
      lineHeight:1.3, wordBreak:'break-word', transition:'opacity 0.15s', opacity:e.riscado?0.55:1 };
    if (e.tipo==='credito')  return {...base, color:'#15803D', background:'#F0FDF4', border:'1px solid #BBF7D0', fontWeight:600};
    if (e.tipo==='debito')   return {...base, color:'#B91C1C', background:'#FEF2F2', border:'1px solid #FECACA', fontWeight:600};
    if (e.tipo==='feriado')  return {...base, color:'#6B7280', background:'#F1F5F9', border:'1px solid #E2E8F0', fontWeight:600, fontStyle:'italic'};
    // servico
    const bg = e.status==='finalizado' ? '#FEF9C3' : '#fff';
    const bc = e.status==='finalizado' ? '#FDE68A' : '#E2E8F0';
    return {...base, color:'#374151', background:bg, border:`1px solid ${bc}`};
  }

  const tiposEntrada = [
    {v:'servico', l:'Serviço / Atendimento'},
    {v:'credito', l:'Crédito (recebimento)'},
    {v:'debito',  l:'Débito (despesa)'},
    {v:'feriado', l:'Feriado / Bloqueio'},
  ];

  const cliOpts = db.clientes.map(c=>({v:c.id,l:c.fantasia}));

  return (
    <div style={{opacity:1}}>
      <PgHeader
        title={`${MESES[mes]} ${ano}`}
        subtitle="Agenda mensal — clique num dia ou use o botão para adicionar"
        actions={<>
          <Btn variant="secondary" icon="chevL" onClick={()=>navMes(-1)}>Anterior</Btn>
          <Btn variant="secondary" onClick={()=>{setMes(hoje.getMonth());setAno(hoje.getFullYear());}}>Hoje</Btn>
          <Btn variant="secondary" icon="chevR" onClick={()=>navMes(1)}>Próximo</Btn>
          <Btn icon="plus" onClick={()=>openModal(null)}>Novo Compromisso</Btn>
        </>}
      />

      <Card style={{padding:0,overflow:'hidden'}}>
        {/* HEADER DIAS */}
        <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',background:'#0D1B2A'}}>
          {DIAS_SEMANA.map((d,i)=>(
            <div key={d} style={{padding:'10px 6px',textAlign:'center',fontSize:11,fontWeight:700,
              color:i===0||i===6?'rgba(248,113,113,0.9)':'rgba(255,255,255,0.6)',
              letterSpacing:'0.06em',textTransform:'uppercase'}}>
              {d}
            </div>
          ))}
        </div>

        {/* CELLS */}
        <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',borderTop:'1px solid #E8EDF4'}}>
          {diasDoMes.map((d, i) => {
            if (d===null) return <div key={`e${i}`} style={{minHeight:110,background:'#F8FAFC',borderRight:'1px solid #E8EDF4',borderBottom:'1px solid #E8EDF4'}}></div>;
            const entries  = entradasDia(d);
            const isHoje   = d===hoje.getDate() && mes===hoje.getMonth() && ano===hoje.getFullYear();
            const isFeriado = entries.some(e=>e.tipo==='feriado');
            const isFim    = i%7===0||i%7===6;
            const saldoDia = entries.find(e=>e.tipo==='saldo');
            const credDia  = entries.filter(e=>e.tipo==='credito').reduce((s,e)=>s+(e.valor||0),0);
            const debDia   = entries.filter(e=>e.tipo==='debito').reduce((s,e)=>s+(e.valor||0),0);

            return (
              <div key={d}
                style={{ minHeight:110, padding:6, borderRight:'1px solid #E8EDF4', borderBottom:'1px solid #E8EDF4',
                  background: isFeriado?'#FFFBEB': isFim?'#FAFBFC':'#fff',
                  position:'relative', transition:'background 0.1s' }}
                onMouseEnter={e=>{ if(!isFeriado&&!isFim) e.currentTarget.style.background='#F5F9FF'; }}
                onMouseLeave={e=>{ e.currentTarget.style.background = isFeriado?'#FFFBEB':isFim?'#FAFBFC':'#fff'; }}>

                {/* Day header */}
                <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:4}}>
                  <span style={{
                    width:24, height:24, borderRadius:6, display:'inline-flex', alignItems:'center', justifyContent:'center',
                    fontSize:12, fontWeight: isHoje?800:600,
                    background: isHoje?'#1E6FD9':'transparent',
                    color: isHoje?'#fff': isFim?'#9CA3AF':'#374151'
                  }}>{d}</span>

                  {/* Saldo diário (admin only) */}
                  {isAdmin && (credDia > 0 || debDia > 0) && (
                    <span style={{fontSize:9,fontWeight:700,color:'#15803D',background:'#F0FDF4',padding:'1px 5px',borderRadius:4}}>
                      {fmt.money(credDia - debDia).replace('R$\u00a0','')}
                    </span>
                  )}
                </div>

                {/* Entries */}
                <div>
                  {entries.filter(e=>e.tipo!=='saldo').slice(0,5).map(e => {
                    const cli = db.clientes.find(c=>c.id===e.clienteId);
                    const hasVal = e.valor && (e.tipo==='credito'||e.tipo==='debito');
                    return (
                      <div key={e.id} style={entryStyle(e)}
                        onClick={ev=>{ ev.stopPropagation(); openModal(d,e); }}
                        onDoubleClick={ev=>{ ev.stopPropagation(); if(e.tipo==='servico') toggleFinalizado(e); else toggleRiscado(e); }}
                        title={`${e.desc}${hasVal?' — '+fmt.money(e.valor):''}  |  Duplo-clique para ${e.tipo==='servico'?'finalizar/reabrir':'riscar/remover traço'}`}>
                        <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                          {hasVal && isAdmin ? `${fmt.money(e.valor).replace('R$\u00a0','R$ ')} ` : ''}
                          {e.desc}
                        </span>
                        {e.status==='finalizado' && e.tipo==='servico' && <span style={{fontSize:8,background:'#FDE68A',color:'#92400E',padding:'1px 4px',borderRadius:3,fontWeight:700,flexShrink:0}}>OK</span>}
                        {!isAdmin && (e.tipo==='credito'||e.tipo==='debito') && <span style={{fontSize:9,opacity:0.5}}>🔒</span>}
                      </div>
                    );
                  })}
                  {entries.length > 5 && <div style={{fontSize:10,color:'#9CA3AF',padding:'2px 4px'}}>+{entries.length-5} mais...</div>}
                </div>

                {/* ADD BUTTON */}
                <button
                  onClick={()=>openModal(d)}
                  style={{position:'absolute',bottom:4,right:4,width:20,height:20,borderRadius:5,background:'#1E6FD9',border:'none',color:'#fff',fontSize:14,cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',opacity:0,transition:'opacity 0.2s'}}
                  onMouseEnter={e=>e.currentTarget.style.opacity=1} onMouseLeave={e=>e.currentTarget.style.opacity=0}
                  title="Adicionar entrada">+</button>
              </div>
            );
          })}
        </div>

        {/* FOOTER TOTAIS */}
        {isAdmin && (
          <div style={{display:'flex',alignItems:'center',gap:0,background:'#0D1B2A',padding:'12px 20px'}}>
            <div style={{flex:1,display:'flex',gap:32}}>
              <div>
                <span style={{fontSize:10,fontWeight:700,color:'rgba(255,255,255,0.4)',textTransform:'uppercase',letterSpacing:'0.06em'}}>Débitos do mês</span>
                <div style={{fontSize:16,fontWeight:800,color:'#F87171',marginTop:2}}>{fmt.money(totais.debitos)}</div>
              </div>
              <div>
                <span style={{fontSize:10,fontWeight:700,color:'rgba(255,255,255,0.4)',textTransform:'uppercase',letterSpacing:'0.06em'}}>Créditos do mês</span>
                <div style={{fontSize:16,fontWeight:800,color:'#4ADE80',marginTop:2}}>{fmt.money(totais.creditos)}</div>
              </div>
              <div>
                <span style={{fontSize:10,fontWeight:700,color:'rgba(255,255,255,0.4)',textTransform:'uppercase',letterSpacing:'0.06em'}}>Saldo</span>
                <div style={{fontSize:16,fontWeight:800,color:totais.creditos-totais.debitos>=0?'#60A5FA':'#F87171',marginTop:2}}>{fmt.money(totais.creditos-totais.debitos)}</div>
              </div>
            </div>
            <div style={{textAlign:'right'}}>
              <span style={{fontSize:10,fontWeight:700,color:'rgba(255,255,255,0.4)',textTransform:'uppercase',letterSpacing:'0.06em'}}>Faturamento</span>
              <div style={{fontSize:16,fontWeight:800,color:'#fff',marginTop:2}}>{fmt.money(totais.creditos)}</div>
            </div>
          </div>
        )}
      </Card>

      {/* LEGENDA */}
      <div style={{display:'flex',gap:16,marginTop:12,flexWrap:'wrap'}}>
        {[['#F0FDF4','#BBF7D0','#15803D','Crédito'],['#FEF2F2','#FECACA','#B91C1C','Débito'],
          ['#FEF9C3','#FDE68A','#92400E','Serviço finalizado'],['#fff','#E2E8F0','#374151','Serviço agendado'],
          ['#FFFBEB','#FDE68A','#92400E','Feriado / Bloqueio']].map(([bg,border,c,label])=>(
          <div key={label} style={{display:'flex',alignItems:'center',gap:6}}>
            <div style={{width:16,height:12,borderRadius:3,background:bg,border:`1.5px solid ${border}`}}></div>
            <span style={{fontSize:11,color:'#6B7280'}}>{label}</span>
          </div>
        ))}
        <span style={{fontSize:11,color:'#9CA3AF',marginLeft:'auto'}}>Duplo-clique: finalizar / traço</span>
      </div>

      {/* MODAL ENTRADA */}
      <Modal open={modal} onClose={()=>setModal(false)}
        title={editando?'Editar compromisso':'Novo compromisso'}
        width={480}
        footer={<>
          {editando && <Btn variant="danger" icon="trash" onClick={()=>{excluir(editando);setModal(false);}}>Excluir</Btn>}
          <div style={{flex:1}}></div>
          <Btn variant="secondary" onClick={()=>setModal(false)}>Cancelar</Btn>
          <Btn icon="check" onClick={salvar}>Salvar</Btn>
        </>}>

        <Grid cols={2} gap={14}>
          <FormField label="Data" required>
            <Inp type="date" value={form.data} onChange={v=>setForm(f=>({...f,data:v}))}/>
          </FormField>
          <FormField label="Tipo" required>
            <Sel value={form.tipo} onChange={v=>setForm(f=>({...f,tipo:v}))} options={tiposEntrada}/>
          </FormField>
          <FormField label="Descrição" required col="1/-1">
            <Inp value={form.desc} onChange={v=>setForm(f=>({...f,desc:v}))} placeholder="Ex: Cliente XYZ — OS_20260001"/>
          </FormField>
          {(form.tipo==='credito'||form.tipo==='debito') && <>
            <FormField label={isAdmin?"Valor (R$)":"Valor"} help={!isAdmin?"Visível apenas para o Administrador":undefined}>
              <Inp value={form.valor} onChange={v=>setForm(f=>({...f,valor:v}))} type="number" min="0" step="0.01" placeholder="0,00" disabled={!isAdmin}/>
            </FormField>
          </>}
          {form.tipo!=='feriado' && <FormField label="Cliente">
            <Sel value={form.clienteId} onChange={v=>setForm(f=>({...f,clienteId:v}))} options={cliOpts} placeholder="Selecionar cliente..."/>
          </FormField>}
          <FormField label="Status">
            <Sel value={form.status} onChange={v=>setForm(f=>({...f,status:v}))} options={[
              {v:'agendado',l:'Agendado'},{v:'finalizado',l:'Finalizado'},{v:'feriado',l:'Feriado'},{v:'cancelado',l:'Cancelado'}]}/>
          </FormField>
          {editando && <FormField label="">
            <label style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer',fontSize:14,color:'#374151'}}>
              <input type="checkbox" checked={!!form.riscado} onChange={e=>setForm(f=>({...f,riscado:e.target.checked}))} style={{width:16,height:16}}/>
              Marcar com traço (liquidado)
            </label>
          </FormField>}
        </Grid>
      </Modal>
    </div>
  );
}

Object.assign(window, { Agenda });
