// Financeiro page with SVG charts

const { useState: finState } = React;

/* ── SVG Line chart ── */
function LineChart({ datasets, width=680, height=240, paddingL=55, paddingT=16, paddingR=20, paddingB=36, maxVal=65 }) {
  const cW = width - paddingL - paddingR;
  const cH = height - paddingT - paddingB;
  const labels = FIN_MONTHS;
  const n = labels.length;

  function toXY(val, idx) {
    const x = paddingL + (idx / (n - 1)) * cW;
    const y = paddingT + cH - (Math.max(0, val) / maxVal) * cH;
    return [x, y];
  }

  function makePath(data) {
    return data.map((v, i) => {
      const [x, y] = toXY(v, i);
      return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
    }).join(' ');
  }

  const yTicks = [0, 15, 30, 45, 60];

  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} style={{ display:'block' }}>
      {/* Grid lines */}
      {yTicks.map(v => {
        const y = paddingT + cH - (v / maxVal) * cH;
        return (
          <g key={v}>
            <line x1={paddingL} x2={width - paddingR} y1={y} y2={y} stroke="#f0f0f0" strokeWidth="1" />
            <text x={paddingL - 6} y={y + 4} textAnchor="end" fontSize="11" fill="#9ca3af">R${v}k</text>
          </g>
        );
      })}
      {/* X labels */}
      {labels.map((l, i) => {
        const x = paddingL + (i / (n - 1)) * cW;
        return <text key={l} x={x} y={height - 4} textAnchor="middle" fontSize="11" fill="#9ca3af">{l}</text>;
      })}
      {/* Lines */}
      {datasets.map(ds => (
        <path key={ds.label} d={makePath(ds.data)} fill="none" stroke={ds.color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" strokeDasharray={ds.dashed ? '6 4' : undefined} />
      ))}
      {/* Dots on last point */}
      {datasets.map(ds => {
        const [x, y] = toXY(ds.data[ds.data.length - 1], ds.data.length - 1);
        return <circle key={ds.label + '-dot'} cx={x} cy={y} r="4" fill={ds.color} />;
      })}
    </svg>
  );
}

/* ── Cash closing chart (cumulative with projection) ── */
function CashChart({ width=680, height=220, paddingL=55, paddingT=16, paddingR=20, paddingB=32, maxVal=42 }) {
  const cW = width - paddingL - paddingR;
  const cH = height - paddingT - paddingB;
  const days = 30;
  // Actual data up to day 20
  const actual = Array.from({ length: 21 }, (_, i) => Math.min(28, (i / 20) * 28 + (Math.sin(i * 0.8) * 1.5)));
  // Projection from day 20 to 30
  const proj = Array.from({ length: 11 }, (_, i) => 28 + (i / 10) * 11);

  function toXY(val, day) {
    const x = paddingL + (day / days) * cW;
    const y = paddingT + cH - (val / maxVal) * cH;
    return [x, y];
  }
  function makePath(data, startDay) {
    return data.map((v, i) => {
      const [x, y] = toXY(v, startDay + i);
      return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
    }).join(' ');
  }

  const yTicks = [0, 10, 20, 30, 40];
  const xTicks = [0, 5, 10, 15, 20, 25, 30];

  // Today marker at day 20
  const [tx, ] = toXY(28, 20);

  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} style={{ display:'block' }}>
      {yTicks.map(v => {
        const y = paddingT + cH - (v / maxVal) * cH;
        return (
          <g key={v}>
            <line x1={paddingL} x2={width - paddingR} y1={y} y2={y} stroke="#f0f0f0" strokeWidth="1" />
            <text x={paddingL - 6} y={y + 4} textAnchor="end" fontSize="11" fill="#9ca3af">R${v}k</text>
          </g>
        );
      })}
      {xTicks.map(d => {
        const x = paddingL + (d / days) * cW;
        return <text key={d} x={x} y={height - 4} textAnchor="middle" fontSize="11" fill="#9ca3af">{d}</text>;
      })}
      {/* Today vertical line */}
      <line x1={tx} x2={tx} y1={paddingT} y2={paddingT + cH} stroke="#d1d5db" strokeWidth="1" strokeDasharray="4 3" />
      {/* Actual line */}
      <path d={makePath(actual, 0)} fill="none" stroke="#16a34a" strokeWidth="2" strokeLinejoin="round" />
      {/* Projection dashed */}
      <path d={makePath(proj, 20)} fill="none" stroke="#16a34a" strokeWidth="2" strokeLinejoin="round" strokeDasharray="6 4" />
      {/* Today dot */}
      <circle cx={tx} cy={paddingT + cH - (28/maxVal)*cH} r="5" fill="#16a34a" />
    </svg>
  );
}

/* ── Bar chart ── */
function BarChart({ width=680, height=240, paddingL=55, paddingT=16, paddingR=20, paddingB=36, maxVal=42 }) {
  const cW = width - paddingL - paddingR;
  const cH = height - paddingT - paddingB;
  const receitas = [35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35];
  const despesas = [28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28];
  const n = 12;
  const groupW = cW / n;
  const barW = groupW * 0.32;
  const yTicks = [0, 15, 30, 45, 60];

  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} style={{ display:'block' }}>
      {yTicks.map(v => {
        const y = paddingT + cH - (v / maxVal) * cH;
        return (
          <g key={v}>
            <line x1={paddingL} x2={width - paddingR} y1={y} y2={y} stroke="#f0f0f0" strokeWidth="1" />
            <text x={paddingL - 6} y={y + 4} textAnchor="end" fontSize="11" fill="#9ca3af">R${v}k</text>
          </g>
        );
      })}
      {FIN_MONTHS.map((m, i) => {
        const gx = paddingL + i * groupW;
        const midX = gx + groupW / 2;
        const rx = gx + groupW * 0.1;
        const dx = gx + groupW * 0.1 + barW + 3;
        const rh = (receitas[i] / maxVal) * cH;
        const dh = (despesas[i] / maxVal) * cH;
        return (
          <g key={m}>
            <rect x={rx} y={paddingT + cH - rh} width={barW} height={rh} fill="#16a34a" rx="2" />
            <rect x={dx} y={paddingT + cH - dh} width={barW} height={dh} fill="#dc2626" rx="2" opacity="0.75" />
            <text x={midX} y={height - 4} textAnchor="middle" fontSize="10" fill="#9ca3af">{m}</text>
          </g>
        );
      })}
    </svg>
  );
}

/* ── Transaction item ── */
function TransactionItem({ t }) {
  const isEntrada = t.type === 'entrada';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:14, padding:'14px 0', borderBottom:'1px solid #f3f4f6' }}>
      <div style={{
        width:38, height:38, borderRadius:'50%', flexShrink:0,
        background: isEntrada ? '#fef3c7' : '#fee2e2',
        display:'flex', alignItems:'center', justifyContent:'center',
      }}>
        <Icon name={isEntrada ? 'arrowUp' : 'arrowDown'} size={18} color={isEntrada ? '#d97706' : '#dc2626'} />
      </div>
      <div style={{ flex:1 }}>
        <div style={{ fontSize:14, fontWeight:600, color:'#111' }}>{t.category}</div>
        <div style={{ fontSize:12, color:'#6b7280' }}>{t.date} · {t.desc}</div>
      </div>
      <span style={{ fontSize:14, fontWeight:700, color: isEntrada ? '#16a34a' : '#dc2626' }}>
        {isEntrada ? '+' : '-'} R$ {t.amount.toLocaleString('pt-BR', { minimumFractionDigits:2 })}
      </span>
    </div>
  );
}

/* ── Financeiro page ── */
function Financeiro({ setModal }) {
  const totalEntradas = TRANSACTIONS.filter(t => t.type==='entrada').reduce((s,t) => s+t.amount, 0);
  const totalSaidas   = TRANSACTIONS.filter(t => t.type==='saida').reduce((s,t) => s+t.amount, 0);
  const saldo = totalEntradas - totalSaidas;

  const statCards = [
    { label:'Total de Entradas', value:`R$ ${totalEntradas.toLocaleString('pt-BR',{minimumFractionDigits:2})}`, color:'#dc2626' },
    { label:'Total de Saídas',   value:`R$ ${totalSaidas.toLocaleString('pt-BR',{minimumFractionDigits:2})}`,   color:'#dc2626' },
    { label:'Saldo',             value:`R$ ${saldo < 0 ? '-' : ''}${Math.abs(saldo).toLocaleString('pt-BR',{minimumFractionDigits:2})}`, color: saldo < 0 ? '#dc2626' : '#16a34a' },
  ];

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, background:C.pageBg }}>
      <Topbar title="Financeiro" />
      <div style={{ flex:1, overflowY:'auto', padding:'20px 24px', display:'flex', flexDirection:'column', gap:18 }}>

        {/* Stat cards */}
        <div style={{ display:'flex', gap:14 }}>
          {statCards.map(s => (
            <div key={s.label} style={{ flex:1, background:'#fde8e8', borderRadius:8, padding:'16px 20px', boxShadow:'0 1px 3px rgba(0,0,0,0.05)' }}>
              <div style={{ fontSize:10, fontWeight:700, letterSpacing:1, color: s.color, textTransform:'uppercase', marginBottom:6 }}>{s.label}</div>
              <div style={{ fontSize:26, fontWeight:700, color: s.color }}>{s.value}</div>
            </div>
          ))}
        </div>

        {/* Transaction list */}
        <Card style={{ padding:'18px 22px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:4 }}>
            <h3 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>Controle financeiro</h3>
            <div style={{ display:'flex', gap:10 }}>
              <select style={{ fontSize:13, border:'1px solid #e5e7eb', borderRadius:6, padding:'5px 10px', background:'white', cursor:'pointer' }}>
                <option>Mês</option><option>Semana</option><option>Ano</option>
              </select>
              <button style={{ display:'flex', alignItems:'center', gap:5, padding:'6px 14px', border:'1px solid #e5e7eb', borderRadius:6, background:'white', cursor:'pointer', fontSize:13, color:'#374151' }}>
                <Icon name="download" size={14} color="#374151" /> Exportar
              </button>
              <button onClick={() => setModal('lancamento')}
                style={{ display:'flex', alignItems:'center', gap:5, padding:'6px 16px', background:C.primary, color:'white', border:'none', borderRadius:6, cursor:'pointer', fontSize:13, fontWeight:600 }}>
                + Novo lançamento
              </button>
            </div>
          </div>
          {TRANSACTIONS.map(t => <TransactionItem key={t.id} t={t} />)}
        </Card>

        {/* Line chart */}
        <Card style={{ padding:'18px 22px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <h3 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>Evolução Financeira Mensal</h3>
            <select style={{ fontSize:13, border:'1px solid #e5e7eb', borderRadius:6, padding:'5px 10px', background:'white', cursor:'pointer' }}>
              <option>Mês</option><option>Ano</option>
            </select>
          </div>
          <LineChart datasets={[
            { label:'Entradas', data: FIN_ENTRADAS, color:'#16a34a' },
            { label:'Saídas',   data: FIN_SAIDAS,   color:'#dc2626' },
            { label:'Saldo',    data: FIN_SALDO,    color:'#2563a8' },
          ]} />
          <div style={{ display:'flex', justifyContent:'center', gap:20, marginTop:8 }}>
            {[['#16a34a','Entradas'],['#dc2626','Saídas'],['#2563a8','Saldo']].map(([col,lbl]) => (
              <div key={lbl} style={{ display:'flex', alignItems:'center', gap:6 }}>
                <div style={{ width:24, height:2, background:col, borderRadius:2 }} />
                <span style={{ fontSize:12, color:'#6b7280' }}>← {lbl}</span>
              </div>
            ))}
          </div>
        </Card>

        {/* Cash closing chart */}
        <Card style={{ padding:'18px 22px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <h3 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>Fechamento de caixa mensal</h3>
            <div style={{ display:'flex', gap:8 }}>
              {['Mês','Todas as unidades','Todas as salas','Diário','Com projeção'].map(opt => (
                <select key={opt} style={{ fontSize:12, border:'1px solid #e5e7eb', borderRadius:6, padding:'4px 8px', background:'white', cursor:'pointer' }}>
                  <option>{opt}</option>
                </select>
              ))}
            </div>
          </div>
          <CashChart />
        </Card>

        {/* Bar chart */}
        <Card style={{ padding:'18px 22px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <h3 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>Receitas e despesas</h3>
            <div style={{ display:'flex', gap:8 }}>
              {['2026','Todas as unidades','Todas as salas'].map(opt => (
                <select key={opt} style={{ fontSize:12, border:'1px solid #e5e7eb', borderRadius:6, padding:'4px 8px', background:'white', cursor:'pointer' }}>
                  <option>{opt}</option>
                </select>
              ))}
            </div>
          </div>
          <BarChart />
          <div style={{ display:'flex', justifyContent:'center', gap:20, marginTop:8 }}>
            {[['#16a34a','Receitas'],['#dc2626','Despesas']].map(([col,lbl]) => (
              <div key={lbl} style={{ display:'flex', alignItems:'center', gap:6 }}>
                <div style={{ width:16, height:10, background:col, borderRadius:2, opacity: lbl==='Despesas'?0.75:1 }} />
                <span style={{ fontSize:12, color:'#6b7280' }}>← {lbl}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Financeiro });
