/* global React */

// ============================================================
// RADAR CIRCULAR — 24h × 7 dias em formato radial
// Cada dia é um anel; cada hora é um setor de 15°.
// ============================================================
function RadarCircular({ blocos, semanaInicio, hospitais }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  const semIni = semanaInicio || window.inicioSemana(window.HOJE_ISO);
  const SIZE = 480;
  const CX = SIZE / 2;
  const CY = SIZE / 2;
  const INNER = 70;       // raio do círculo central
  const OUTER = 220;      // raio externo
  const RING = (OUTER - INNER) / 7; // espessura de cada dia

  // Para cada bloco, gera arcos preenchendo a faixa do dia correspondente
  const polarToCartesian = (cx, cy, r, angleDeg) => {
    const rad = (angleDeg - 90) * Math.PI / 180;
    return { x: cx + r * Math.cos(rad), y: cy + r * Math.sin(rad) };
  };
  const arcPath = (cx, cy, rIn, rOut, a1, a2) => {
    const p1 = polarToCartesian(cx, cy, rOut, a2);
    const p2 = polarToCartesian(cx, cy, rOut, a1);
    const p3 = polarToCartesian(cx, cy, rIn, a1);
    const p4 = polarToCartesian(cx, cy, rIn, a2);
    const large = (a2 - a1) <= 180 ? 0 : 1;
    return `M ${p1.x} ${p1.y} A ${rOut} ${rOut} 0 ${large} 0 ${p2.x} ${p2.y} L ${p3.x} ${p3.y} A ${rIn} ${rIn} 0 ${large} 1 ${p4.x} ${p4.y} Z`;
  };

  const renderBloco = (b, dia, horaIni, dur, key) => {
    const rIn = INNER + dia * RING + 2;
    const rOut = INNER + (dia + 1) * RING - 2;
    const a1 = horaIni * 15;
    const a2 = (horaIni + dur) * 15;
    let fill, opacity = 1;
    if (b.tipo === 'plantao') {
      fill = window.getHospital(b.hospitalId, HOSPS).cor;
    } else if (b.tipo === 'deslocamento') {
      fill = window.getHospital(b.hospitalDestinoId, HOSPS).cor;
      opacity = 0.5;
    } else if (b.tipo === 'sono') {
      fill = '#A4D498';
      opacity = 0.6;
    } else if (b.tipo === 'trocado') {
      fill = '#A299CB';
      opacity = 0.5;
    } else {
      fill = 'var(--line-2)';
    }
    return <path key={key} d={arcPath(CX, CY, rIn, rOut, a1, a2)} fill={fill} opacity={opacity}/>;
  };

  // Mapear bloco -> índice de dia (0=Seg, 6=Dom) dentro da semana ancorada em semIni
  const diaIdxOf = (iso) => {
    const dias = Math.round((window.fromISO(iso) - window.fromISO(semIni)) / 86400000);
    return dias;
  };

  const arcs = [];
  blocos.forEach(b => {
    if (!b.data) return;
    const dia = diaIdxOf(b.data);
    if (dia < 0 || dia > 6) return;
    const fim = b.horaInicio + b.duracao;
    if (fim <= 24) {
      arcs.push(renderBloco(b, dia, b.horaInicio, b.duracao, `${b.id}-a`));
    } else {
      arcs.push(renderBloco(b, dia, b.horaInicio, 24 - b.horaInicio, `${b.id}-a`));
      if (dia < 6) {
        arcs.push(renderBloco(b, dia + 1, 0, fim - 24, `${b.id}-b`));
      }
    }
  });

  // Anéis de dia (background)
  const rings = window.DIAS_SEMANA.map((_, i) => (
    <circle key={i} cx={CX} cy={CY} r={INNER + i * RING}
      fill="none" stroke="var(--line)" strokeWidth="1"/>
  ));

  // Linhas de hora (radiais a cada 6h)
  const hourLines = [0, 6, 12, 18].map(h => {
    const a = h * 15;
    const p1 = polarToCartesian(CX, CY, INNER, a);
    const p2 = polarToCartesian(CX, CY, OUTER, a);
    return <line key={h} x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y}
      stroke="var(--line)" strokeWidth="1" strokeDasharray="2 4"/>;
  });

  // Labels de hora externas
  const hourLabels = [0, 6, 12, 18].map(h => {
    const a = h * 15;
    const p = polarToCartesian(CX, CY, OUTER + 18, a);
    const labelMap = {0: '00h', 6: '06h', 12: '12h', 18: '18h'};
    return <text key={h} x={p.x} y={p.y} textAnchor="middle" dominantBaseline="middle"
      fontFamily="var(--font-body)" fontSize="11" fontWeight="600"
      fill="var(--ink-3)">{labelMap[h]}</text>;
  });

  // Labels de dia: cada anel ganha sua etiqueta a um ângulo levemente diferente
  // (em torno de 270° = esquerda), espalhando-os para não sobrepor.
  const dayLabels = window.DIAS_SEMANA.map((d, i) => {
    const r = INNER + (i + 0.5) * RING;
    const ang = 247 + i * 6; // 247° → 283°, ~36° de leque do lado esquerdo
    const p = polarToCartesian(CX, CY, r, ang);
    return (
      <g key={d}>
        <rect x={p.x - 14} y={p.y - 7} width="28" height="14" rx="7"
          fill="var(--bg)" stroke="var(--line-2)" strokeWidth="0.5"/>
        <text x={p.x} y={p.y} textAnchor="middle" dominantBaseline="middle"
          fontFamily="var(--font-body)" fontSize="9" fontWeight="700"
          fill="var(--ink-2)" letterSpacing="0.05em">{d.toUpperCase()}</text>
      </g>
    );
  });

  return (
    <div style={{
      background: 'var(--bg)',
      borderRadius: 'var(--r-lg)',
      boxShadow: 'var(--shadow-sm)',
      padding: 'var(--s-7)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexDirection: 'column', gap: 'var(--s-4)',
    }}>
      <div style={{textAlign:'center', marginBottom: 'var(--s-2)'}}>
        <div className="eyebrow">Visão radial</div>
        <h3 className="h3" style={{marginTop: 4}}>Sua semana, em 360°</h3>
        <p className="small" style={{marginTop: 4, maxWidth: 360}}>
          Cada anel é um dia, do centro (segunda) à borda (domingo). Cada volta completa são 24h.
        </p>
      </div>
      <svg width={SIZE} height={SIZE} viewBox={`0 0 ${SIZE} ${SIZE}`}>
        {rings}
        {arcs}
        {hourLines}
        {hourLabels}
        {dayLabels}
        <circle cx={CX} cy={CY} r={INNER - 2} fill="var(--bg-alt)"/>
        <text x={CX} y={CY - 8} textAnchor="middle" fontFamily="var(--font-display)" fontSize="32" fontWeight="500" fill="var(--ink)">{Math.round(window.calcCargaTotal(blocos))}h</text>
        <text x={CX} y={CY + 14} textAnchor="middle" fontFamily="var(--font-body)" fontSize="11" fill="var(--ink-2)">na semana</text>
      </svg>
    </div>
  );
}

// ============================================================
// HISTÓRICO 4 SEMANAS — barras de carga + cadeia
// ============================================================
function HistoricoSemanas() {
  const max = 80;
  return (
    <div style={{
      background: 'var(--bg)',
      borderRadius: 'var(--r-lg)',
      boxShadow: 'var(--shadow-sm)',
      padding: 'var(--s-6)',
    }}>
      <div className="eyebrow">Tendência</div>
      <h3 className="h3" style={{marginTop: 4}}>Últimas 4 semanas</h3>
      <p className="small" style={{marginTop: 4, marginBottom: 'var(--s-7)'}}>
        Carga total e a maior cadeia contínua de cada semana.
      </p>
      <div style={{display: 'flex', alignItems: 'flex-end', gap: 'var(--s-4)', height: 220, paddingTop: 32}}>
        {window.SEMANAS_HISTORICO.map((s, i) => {
          const cls = window.classifyCarga(s.total);
          const barH = (s.total / max) * 100;
          const chainH = (s.chain / max) * 100;
          const barColor = cls.zone === 'ok' ? 'var(--ok)' : cls.zone === 'warn' ? 'var(--warn)' : 'var(--err)';
          return (
            <div key={i} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap: 8}}>
              <div style={{
                fontFamily: 'var(--font-display)',
                fontSize: 22, fontWeight: 500,
                color: s.current ? 'var(--ink)' : 'var(--ink-3)',
              }}>{s.total}h</div>
              <div style={{
                position: 'relative',
                width: '100%', maxWidth: 80, height: 200,
                background: 'var(--bg-alt)',
                borderRadius: 'var(--r-sm)',
                overflow: 'hidden',
                border: s.current ? `2px solid ${barColor}` : '1px solid var(--line)',
              }}>
                <div style={{
                  position: 'absolute', bottom: 0, left: 0, right: 0,
                  height: `${barH}%`,
                  background: barColor,
                  opacity: s.current ? 0.85 : 0.4,
                  transition: 'all var(--dur-2) var(--ease)',
                }}/>
                {/* marcador da cadeia */}
                <div style={{
                  position: 'absolute', left: 6, right: 6,
                  bottom: `${chainH}%`,
                  height: 2,
                  background: 'var(--ink)',
                  opacity: 0.55,
                }}/>
                <div style={{
                  position: 'absolute', right: 6,
                  bottom: `calc(${chainH}% + 4px)`,
                  fontSize: 9, fontWeight: 700,
                  color: 'var(--ink-2)',
                  fontFamily: 'var(--font-body)',
                }}>{s.chain}h</div>
              </div>
              <div style={{
                fontSize: 11, color: 'var(--ink-2)', textAlign: 'center',
                fontWeight: s.current ? 700 : 500,
              }}>{s.label}</div>
            </div>
          );
        })}
      </div>
      <div style={{
        marginTop: 'var(--s-5)',
        padding: 'var(--s-4)',
        background: 'var(--colo-coral-50)',
        borderRadius: 'var(--r-md)',
        display: 'flex', gap: 'var(--s-3)', alignItems: 'flex-start',
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: 999,
          background: 'var(--err)',
          display: 'grid', placeItems: 'center', flexShrink: 0,
          color: 'white', fontFamily: 'var(--font-display)', fontSize: 18,
        }}>↗</div>
        <div>
          <div style={{fontWeight: 700, fontSize: 14, color: 'var(--ink)'}}>
            +9h em relação à semana passada
          </div>
          <div className="small" style={{marginTop: 2}}>
            É o quarto aumento consecutivo. Considere proteger o próximo fim de semana.
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// LISTA CRONOLÓGICA — uma das 7 colunas de uma vez (mobile-first)
// ============================================================
function ListaDoDia({ blocos, diaISO, hospitais, onSelectBloco }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  const iso = diaISO || window.HOJE_ISO;
  const doDia = blocos
    .filter(b => b.data === iso)
    .sort((a, b) => a.horaInicio - b.horaInicio);
  const dt = window.fromISO(iso);
  const diaSemana = window.diaSemanaBR(iso);

  return (
    <div style={{
      background: 'var(--bg)',
      borderRadius: 'var(--r-lg)',
      boxShadow: 'var(--shadow-sm)',
      padding: 'var(--s-5)',
    }}>
      <div className="eyebrow">Vista cronológica</div>
      <h3 className="h3" style={{marginTop: 4, marginBottom: 'var(--s-4)'}}>
        {window.DIAS_COMPLETO[diaSemana]}, {dt.getDate()} {window.MESES_CURTO[dt.getMonth()]}
      </h3>

      {doDia.length === 0 && (
        <p className="small" style={{padding: 'var(--s-5) 0', textAlign: 'center'}}>
          Nada agendado. Aproveite.
        </p>
      )}

      <div style={{display: 'flex', flexDirection: 'column', gap: 'var(--s-2)'}}>
        {doDia.map(b => {
          const fim = b.horaInicio + b.duracao;
          let titulo, sub, tag, color, wash;
          if (b.tipo === 'plantao') {
            const h = window.getHospital(b.hospitalId, HOSPS);
            titulo = h.nome;
            sub = h.endereco;
            color = h.corDeep;
            wash = h.corWash;
            tag = `${b.duracao}h`;
          } else if (b.tipo === 'deslocamento') {
            const h = window.getHospital(b.hospitalDestinoId, HOSPS);
            titulo = `Deslocamento até ${h.abrev}`;
            sub = `Trânsito até ${h.endereco}`;
            color = h.corDeep;
            wash = h.corWash;
            tag = `${Math.round(b.duracao * 60)}min`;
          } else if (b.tipo === 'sono') {
            titulo = 'Sono protegido';
            sub = 'Janela de descanso planejada';
            color = '#5A6E50';
            wash = 'var(--colo-sage-50)';
            tag = `${b.duracao}h`;
          } else if (b.tipo === 'trocado') {
            titulo = 'Trocado';
            sub = `Com ${b.trocadoCom}`;
            color = '#A299CB';
            wash = 'var(--colo-lavender-50)';
            tag = `${b.duracao}h`;
          } else {
            titulo = 'Cedido';
            sub = `Para ${b.cedidoPara}`;
            color = 'var(--ink-2)';
            wash = 'var(--bg-alt)';
            tag = '—';
          }
          return (
            <button key={b.id} onClick={() => onSelectBloco(b)}
              style={{
                display: 'grid',
                gridTemplateColumns: '60px 1fr auto',
                gap: 'var(--s-3)',
                padding: 'var(--s-3) var(--s-4)',
                background: wash,
                border: '1px solid var(--line)',
                borderLeft: `3px solid ${color}`,
                borderRadius: 'var(--r-md)',
                cursor: 'pointer',
                textAlign: 'left',
                fontFamily: 'var(--font-body)',
                color: 'var(--ink)',
                transition: 'transform var(--dur-1) var(--ease)',
              }}
              onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-1px)'}
              onMouseLeave={(e) => e.currentTarget.style.transform = 'none'}
            >
              <div>
                <div style={{fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600, color}}>
                  {window.fmtHora(b.horaInicio)}
                </div>
                <div style={{fontSize: 11, color: 'var(--ink-3)', marginTop: 2}}>
                  → {window.fmtHora(fim)}
                </div>
              </div>
              <div style={{minWidth: 0}}>
                <div style={{fontWeight: 700, fontSize: 14, lineHeight: 1.2}}>{titulo}</div>
                <div style={{fontSize: 12, color: 'var(--ink-2)', marginTop: 2}}>{sub}</div>
              </div>
              <div style={{
                fontSize: 11, fontWeight: 700,
                color: color,
                alignSelf: 'center',
                whiteSpace: 'nowrap',
              }}>{tag}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============================================================
// MINI-MAPA DE BRASÍLIA — abstrato; 3 hospitais + tempos
// ============================================================
function MiniMapa({ hospitais }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  // SVG estilizado do quadrilátero de Brasília (Plano Piloto + arredores)
  return (
    <div style={{
      background: 'var(--bg)',
      borderRadius: 'var(--r-lg)',
      boxShadow: 'var(--shadow-sm)',
      padding: 'var(--s-6)',
    }}>
      <div className="eyebrow">Mapa</div>
      <h3 className="h3" style={{marginTop: 4}}>Seus três hospitais</h3>
      <p className="small" style={{marginTop: 4, marginBottom: 'var(--s-5)'}}>
        Tempos médios de deslocamento esta semana.
      </p>

      <div style={{
        position: 'relative',
        width: '100%', aspectRatio: '4 / 3',
        background: 'var(--bg-alt)',
        borderRadius: 'var(--r-md)',
        overflow: 'hidden',
        border: '1px solid var(--line)',
      }}>
        <svg viewBox="0 0 400 300" style={{width:'100%', height:'100%', display:'block'}}>
          {/* Lago Paranoá estilizado */}
          <path d="M 240 60 Q 280 90 290 140 Q 300 200 270 240 Q 240 270 200 250 L 220 200 Q 250 180 240 140 Q 230 110 220 90 Z"
            fill="#9BC2E7" opacity="0.25"/>
          {/* Eixo monumental — abstrato */}
          <line x1="60" y1="150" x2="240" y2="150" stroke="var(--line-2)" strokeWidth="1.5" strokeDasharray="3 3"/>
          {/* Asas (curvas) */}
          <path d="M 60 150 Q 100 80 200 100" fill="none" stroke="var(--line-2)" strokeWidth="1.5"/>
          <path d="M 60 150 Q 100 220 200 200" fill="none" stroke="var(--line-2)" strokeWidth="1.5"/>

          {/* Linhas de conexão entre hospitais */}
          <line x1="120" y1="200" x2="180" y2="80" stroke="var(--ink-3)" strokeWidth="1" strokeDasharray="2 4" opacity="0.5"/>
          <line x1="180" y1="80" x2="60" y2="240" stroke="var(--ink-3)" strokeWidth="1" strokeDasharray="2 4" opacity="0.5"/>
          <line x1="120" y1="200" x2="60" y2="240" stroke="var(--ink-3)" strokeWidth="1" strokeDasharray="2 4" opacity="0.5"/>

          {/* HSL — Asa Sul (sand) */}
          <g transform="translate(120, 200)">
            <circle r="22" fill="#E8C79A" stroke="white" strokeWidth="3"/>
            <text textAnchor="middle" dy="4" fontFamily="var(--font-body)" fontSize="11" fontWeight="700" fill="#7A5A2E">HSL</text>
          </g>
          <text x="120" y="240" textAnchor="middle" fontSize="10" fill="var(--ink-2)" fontFamily="var(--font-body)">Asa Sul</text>

          {/* HBDF — Asa Norte (blue) */}
          <g transform="translate(180, 80)">
            <circle r="22" fill="#9BC2E7" stroke="white" strokeWidth="3"/>
            <text textAnchor="middle" dy="4" fontFamily="var(--font-body)" fontSize="10" fontWeight="700" fill="#2D5276">HBDF</text>
          </g>
          <text x="180" y="50" textAnchor="middle" fontSize="10" fill="var(--ink-2)" fontFamily="var(--font-body)">Asa Norte</text>

          {/* HDS — Águas Claras (coral) */}
          <g transform="translate(60, 240)">
            <circle r="22" fill="#E7A59C" stroke="white" strokeWidth="3"/>
            <text textAnchor="middle" dy="4" fontFamily="var(--font-body)" fontSize="11" fontWeight="700" fill="#8E3F33">HDS</text>
          </g>
          <text x="60" y="280" textAnchor="middle" fontSize="10" fill="var(--ink-2)" fontFamily="var(--font-body)">Águas Claras</text>

          {/* Tempos médios em pequenos rótulos no meio das linhas */}
          <g>
            <rect x="138" y="130" width="46" height="18" rx="9" fill="var(--bg)" stroke="var(--line-2)"/>
            <text x="161" y="142" textAnchor="middle" fontSize="10" fontWeight="700" fill="var(--ink)" fontFamily="var(--font-body)">45 min</text>
          </g>
          <g>
            <rect x="100" y="155" width="46" height="18" rx="9" fill="var(--bg)" stroke="var(--line-2)"/>
            <text x="123" y="167" textAnchor="middle" fontSize="10" fontWeight="700" fill="var(--ink)" fontFamily="var(--font-body)">35 min</text>
          </g>
          <g>
            <rect x="100" y="220" width="46" height="18" rx="9" fill="var(--bg)" stroke="var(--line-2)"/>
            <text x="123" y="232" textAnchor="middle" fontSize="10" fontWeight="700" fill="var(--ink)" fontFamily="var(--font-body)">22 min</text>
          </g>
        </svg>
      </div>

      <div style={{marginTop: 'var(--s-4)', display: 'flex', flexDirection: 'column', gap: 'var(--s-2)'}}>
        {HOSPS.map(h => (
          <div key={h.id} style={{
            display: 'flex', alignItems: 'center', gap: 'var(--s-3)',
            padding: 'var(--s-2) 0',
          }}>
            <div style={{
              width: 12, height: 12, borderRadius: 999,
              background: h.cor,
            }}/>
            <div style={{flex: 1, fontSize: 13}}>
              <strong>{h.abrev}</strong>
              <span style={{color: 'var(--ink-2)', marginLeft: 8}}>{h.nome}</span>
            </div>
            <span style={{fontSize: 12, color: 'var(--ink-3)'}}>{h.endereco}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { RadarCircular, HistoricoSemanas, ListaDoDia, MiniMapa });
