/* global React */
const { useState: useStateImp, useMemo: useMemoImp, useEffect: useEffectImp } = React;

// =====================================================================
// ImportView — recebe JSON v1, valida, mostra preview, confirma
// =====================================================================
function ImportView({ hospitais, blocos, onImportar, onImportarICS, onCadastrarHospital }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  const [textoJson, setTextoJson] = useStateImp('');
  const [erroParse, setErroParse] = useStateImp(null);
  const [parsed, setParsed] = useStateImp(null);
  const [selecionados, setSelecionados] = useStateImp({});
  const [statusInbox, setStatusInbox] = useStateImp('idle'); // idle | loading | ok | empty | erro
  const [mensagemFinal, setMensagemFinal] = useStateImp(null);
  const [inboxFiles, setInboxFiles] = useStateImp([]);
  const [inboxFileSelecionado, setInboxFileSelecionado] = useStateImp(null);
  const [hospitalParaCadastrar, setHospitalParaCadastrar] = useStateImp(null);

  // ---- Carregar lista do inbox -------------------------------------
  useEffectImp(() => {
    fetch('inbox/index.json', { cache: 'no-cache' })
      .then(r => r.ok ? r.json() : null)
      .then(data => { if (data?.files) setInboxFiles(data.files); })
      .catch(() => {});
  }, []);

  const carregarArquivoInbox = async (file) => {
    setStatusInbox('loading');
    setErroParse(null);
    try {
      const res = await fetch('inbox/' + file, { cache: 'no-cache' });
      if (!res.ok) { setStatusInbox('empty'); return; }
      const txt = await res.text();
      setTextoJson(txt);
      setInboxFileSelecionado(file);
      processarJson(txt);
      setStatusInbox('ok');
    } catch (e) {
      setStatusInbox('erro');
      setErroParse('Não consegui ler o inbox. Você está servindo via HTTP? (não funciona com file://)');
    }
  };

  // ---- Re-anota ao receber novo cadastro de hospital ---------------
  useEffectImp(() => {
    if (parsed && textoJson) processarJson(textoJson);
    // eslint-disable-next-line
  }, [HOSPS.length]);

  // ---- Parse + validação leve --------------------------------------
  const processarJson = (txt) => {
    setErroParse(null);
    setParsed(null);
    if (!txt.trim()) return;
    let data;
    try {
      data = JSON.parse(txt);
    } catch (e) {
      setErroParse('JSON inválido: ' + e.message);
      return;
    }
    if (data.schemaVersion !== 1) {
      setErroParse(`Versão do schema desconhecida: ${data.schemaVersion} (esperado: 1)`);
      return;
    }
    if (!Array.isArray(data.blocks) && !Array.isArray(data.recurrences)) {
      setErroParse('JSON sem "blocks" nem "recurrences".');
      return;
    }

    const blocksAnot = (data.blocks || []).map((b, idx) => {
      const hosp = HOSPS.find(h => h.abrev?.toUpperCase() === (b.hospitalAbrev || '').toUpperCase());
      // Se faltam horaInicio/duracao mas tem turno + hospital cadastrado: resolve
      let horaInicio = b.horaInicio;
      let duracao = b.duracao;
      if (hosp && b.turno && (horaInicio == null || duracao == null)) {
        const t = window.resolverTurno(hosp, b.turno);
        if (t) { horaInicio = t.horaInicio; duracao = t.duracao; }
      }
      const efetivo = { ...b, horaInicio, duracao };
      const projetado = hosp ? { ...efetivo, hospitalId: hosp.id } : efetivo;
      const conflitos = (hosp && horaInicio != null && duracao != null) ? window.detectarConflitos(projetado, blocos || []) : [];
      const cadeia = (hosp && horaInicio != null && duracao != null) ? window.cadeiaSeAdicionar(projetado, blocos || []) : null;
      const dup = hosp && (blocos || []).some(x =>
        x.tipo === 'plantao' &&
        x.hospitalId === hosp.id &&
        x.data === b.data &&
        x.horaInicio === horaInicio &&
        x.duracao === duracao
      );
      const semHorario = horaInicio == null || duracao == null;
      return {
        idx, raw: b, hosp, efetivo,
        flags: {
          semHospital: !hosp,
          semHorario,
          duplicado: dup,
          conflito: conflitos.length > 0,
          cadeia: cadeia && cadeia.horas > 24,
        },
        conflitos, cadeia,
      };
    });

    setParsed({ ...data, _blocksAnot: blocksAnot });
    const sel = {};
    blocksAnot.forEach(b => {
      sel[b.idx] = !b.flags.semHospital && !b.flags.semHorario && !b.flags.duplicado;
    });
    setSelecionados(sel);
  };

  // ---- Hospitais desconhecidos no payload --------------------------
  const hospsDesconhecidos = useMemoImp(() => {
    if (!parsed) return [];
    const set = new Set();
    parsed._blocksAnot.forEach(b => {
      if (b.flags.semHospital && b.raw.hospitalAbrev) set.add(b.raw.hospitalAbrev);
    });
    return [...set];
  }, [parsed]);

  // ---- Submit -------------------------------------------------------
  const importar = () => {
    if (!parsed) return;
    const escolhidos = parsed._blocksAnot
      .filter(b => selecionados[b.idx] && b.hosp && !b.flags.semHorario)
      .map(b => ({
        tipo: b.raw.tipo,
        hospitalId: b.hosp.id,
        data: b.raw.data,
        horaInicio: b.efetivo.horaInicio,
        duracao: b.efetivo.duracao,
        observacao: b.raw.observacao,
        turno: b.raw.turno,
        turnoIncerto: b.raw.turnoIncerto,
      }));
    const recs = (parsed.recurrences || [])
      .map(r => {
        const h = HOSPS.find(h => h.abrev?.toUpperCase() === (r.hospitalAbrev || '').toUpperCase());
        if (!h) return null;
        return {
          id: `r${Date.now()}-${Math.random().toString(36).slice(2,7)}`,
          kind: r.kind,
          diaSemana: r.diaSemana,
          monthlyWeek: r.monthlyWeek,
          horaInicio: r.horaInicio,
          duracao: r.duracao,
          hospitalId: h.id,
          desde: r.desde,
          ate: r.ate,
        };
      })
      .filter(Boolean);
    onImportar(escolhidos, recs, parsed.source || 'JSON');
    setMensagemFinal(`${escolhidos.length} plantão${escolhidos.length === 1 ? '' : 'ões'}${recs.length ? ` + ${recs.length} série${recs.length === 1 ? '' : 's'}` : ''} importado${escolhidos.length === 1 ? '' : 's'} de ${parsed.source || 'JSON'}.`);
    setTextoJson('');
    setParsed(null);
    setSelecionados({});
    setStatusInbox('idle');
    setInboxFileSelecionado(null);
    setTimeout(() => setMensagemFinal(null), 6000);
  };

  const totalSelecionados = parsed
    ? parsed._blocksAnot.filter(b => selecionados[b.idx]).length
    : 0;

  // ---- Render -------------------------------------------------------
  return (
    <div style={{display:'grid', gap: 'var(--s-5)'}}>
      <header>
        <h2 className="h2" style={{fontSize: 28, margin: 0}}>Sincronizar</h2>
        <p className="lede" style={{marginTop: 6, fontSize: 14, maxWidth: 640}}>
          Trazer escalas de outros lugares pra cá, ou levar a sua agenda pro Google/Apple Calendar.
        </p>
      </header>

      {mensagemFinal && (
        <div style={{
          padding: 'var(--s-3) var(--s-4)',
          background: 'var(--ok-bg)',
          color: 'var(--ok)',
          borderRadius: 'var(--r-md)',
          fontWeight: 600, fontSize: 13,
        }}>{mensagemFinal}</div>
      )}

      <div style={{display:'grid', gap: 'var(--s-4)', maxWidth: 980}}>
        {/* ====== IA: subir PDF/foto/screenshot ====== */}
        {window.ImportPDF && (
          <window.ImportPDF
            hospitais={HOSPS}
            doctor="Mariana"
            onJsonExtraido={(json) => {
              setTextoJson(json);
              processarJson(json);
              setInboxFileSelecionado(null);
            }}/>
        )}

        {/* ====== Origem (manual JSON / inbox) ====== */}
        <div style={{
          padding: 'var(--s-5)', background: 'var(--bg)',
          border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
        }}>
          <h3 className="h3" style={{margin: 0, fontSize: 18, marginBottom: 'var(--s-3)'}}>Outras origens</h3>

          {inboxFiles.length > 0 && (
            <div style={{marginBottom: 'var(--s-4)'}}>
              <label className="eyebrow" style={{display:'block', marginBottom: 8}}>Inbox ({inboxFiles.length} arquivo{inboxFiles.length>1?'s':''})</label>
              <div style={{display:'grid', gap: 6}}>
                {inboxFiles.map(f => (
                  <button key={f.file}
                    onClick={() => carregarArquivoInbox(f.file)}
                    style={{
                      display: 'grid',
                      gridTemplateColumns: 'auto 1fr auto',
                      alignItems: 'center', gap: 'var(--s-3)',
                      padding: 'var(--s-3) var(--s-4)',
                      background: inboxFileSelecionado === f.file ? 'var(--colo-blue-50)' : 'var(--bg-alt)',
                      border: '1px solid ' + (inboxFileSelecionado === f.file ? 'var(--colo-blue-tag)' : 'var(--line)'),
                      borderRadius: 'var(--r-md)', cursor: 'pointer',
                      fontFamily: 'var(--font-body)', textAlign: 'left',
                    }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{color:'var(--ink-2)'}}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                    <div>
                      <div style={{fontSize: 13, fontWeight: 600, color: 'var(--ink)'}}>{f.label || f.file}</div>
                      <div className="small" style={{fontSize: 11, color: 'var(--ink-3)'}}>
                        {f.doctor && <>{f.doctor} · </>}{f.file}
                      </div>
                    </div>
                    <span className="small" style={{fontSize: 11, color: 'var(--ink-3)'}}>
                      {inboxFileSelecionado === f.file ? '✓ carregado' : 'abrir'}
                    </span>
                  </button>
                ))}
              </div>
            </div>
          )}

          <label className="eyebrow" style={{display:'block', marginBottom: 8}}>Ou cole o JSON</label>
          <textarea
            value={textoJson}
            onChange={e => { setTextoJson(e.target.value); setInboxFileSelecionado(null); processarJson(e.target.value); }}
            placeholder='{ "schemaVersion": 1, "blocks": [...] }'
            rows={6}
            className="input"
            style={{
              fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
              fontSize: 12, resize: 'vertical', minHeight: 100,
            }}
          />
          {erroParse && (
            <div style={{
              marginTop: 8, padding: 'var(--s-3)',
              background: 'var(--err-bg)', color: 'var(--err)',
              borderRadius: 'var(--r-md)', fontSize: 12, fontWeight: 600,
            }}>{erroParse}</div>
          )}
        </div>

        {/* ====== Hospitais desconhecidos ====== */}
        {hospsDesconhecidos.length > 0 && (
          <div style={{
            padding: 'var(--s-4) var(--s-5)',
            background: 'var(--warn-bg)',
            border: '1px solid var(--warn)',
            borderRadius: 'var(--r-md)',
          }}>
            <div style={{display:'flex', alignItems:'center', gap: 8, marginBottom: 8}}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--warn)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              <strong style={{fontSize: 13, color: 'var(--ink)'}}>
                Hospital{hospsDesconhecidos.length>1?'s':''} não cadastrado{hospsDesconhecidos.length>1?'s':''}
              </strong>
            </div>
            <p className="small" style={{fontSize: 12, marginTop: 0, marginBottom: 8}}>
              O JSON menciona hospital{hospsDesconhecidos.length>1?'s':''} que ainda não está{hospsDesconhecidos.length>1?'ão':''} no app. Cadastre rapidinho aqui pra liberar a importação.
            </p>
            <div style={{display:'flex', flexWrap:'wrap', gap: 6}}>
              {hospsDesconhecidos.map(abrev => (
                <button key={abrev} onClick={() => setHospitalParaCadastrar(abrev)} className="btn"
                  style={{background: 'var(--ink)', color: 'var(--bg)'}}>
                  + Cadastrar {abrev}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* ====== Preview ====== */}
        {parsed && (
          <div style={{
            padding: 'var(--s-5)', background: 'var(--bg)',
            border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
          }}>
            <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom: 'var(--s-3)', flexWrap:'wrap', gap: 8}}>
              <h3 className="h3" style={{margin: 0, fontSize: 18}}>
                Preview · {parsed._blocksAnot.length} plantão{parsed._blocksAnot.length === 1 ? '' : 'ões'}
                {parsed.recurrences?.length ? ` + ${parsed.recurrences.length} série${parsed.recurrences.length === 1 ? '' : 's'}` : ''}
              </h3>
              {parsed.source && (
                <span className="small" style={{fontSize: 11, color: 'var(--ink-3)'}}>
                  origem: <em>{parsed.source}</em>
                  {parsed.doctor && ` · ${parsed.doctor}`}
                </span>
              )}
            </div>
            {parsed.notes && (
              <div className="small" style={{
                fontStyle: 'italic', marginBottom: 'var(--s-3)',
                padding: 'var(--s-3)', background: 'var(--bg-alt)',
                borderRadius: 'var(--r-md)', fontSize: 12,
              }}>
                Nota do agente: {parsed.notes}
              </div>
            )}
            <div style={{
              border: '1px solid var(--line)', borderRadius: 'var(--r-md)',
              maxHeight: 380, overflowY: 'auto',
            }}>
              {parsed._blocksAnot.map(b => (
                <ImportRow key={b.idx} bloco={b} hospitais={HOSPS}
                  checked={!!selecionados[b.idx]}
                  onToggle={() => setSelecionados({...selecionados, [b.idx]: !selecionados[b.idx]})}/>
              ))}
            </div>
            <div style={{
              display:'flex', justifyContent:'space-between', alignItems:'center',
              marginTop: 'var(--s-4)', flexWrap: 'wrap', gap: 8,
            }}>
              <div className="small">
                <button onClick={() => {
                  const todos = {};
                  parsed._blocksAnot.forEach(b => {
                    todos[b.idx] = !b.flags.semHospital && !b.flags.semHorario;
                  });
                  setSelecionados(todos);
                }} style={{
                  border: 0, background: 'transparent', color: 'var(--colo-blue-tag)',
                  cursor:'pointer', textDecoration: 'underline', fontSize: 12, padding: 0, marginRight: 12,
                }}>marcar todos válidos</button>
                <button onClick={() => setSelecionados({})} style={{
                  border: 0, background: 'transparent', color: 'var(--colo-blue-tag)',
                  cursor:'pointer', textDecoration: 'underline', fontSize: 12, padding: 0,
                }}>desmarcar todos</button>
              </div>
              <button onClick={importar}
                disabled={totalSelecionados === 0}
                className="btn"
                style={{
                  background: totalSelecionados > 0 ? 'var(--ink)' : 'var(--ink-3)',
                  color: 'var(--bg)',
                  opacity: totalSelecionados > 0 ? 1 : 0.6,
                  justifyContent: 'center',
                }}>
                Importar {totalSelecionados} {totalSelecionados === 1 ? 'plantão' : 'plantões'}
              </button>
            </div>
          </div>
        )}
      </div>

      {/* ========== Importar do Google/Apple Calendar (.ics) ========== */}
      <ImportarICS onImportarICS={onImportarICS} blocos={blocos}/>

      {/* ========== Exportar pra Google/Apple Calendar (.ics) ========== */}
      <ExportarICS blocos={blocos} hospitais={HOSPS}/>

      {/* ====== Modal de cadastro inline ====== */}
      {hospitalParaCadastrar && (
        <CadastroRapidoHospital
          abrev={hospitalParaCadastrar}
          familiasUsadas={HOSPS.map(h => h.family)}
          onCancelar={() => setHospitalParaCadastrar(null)}
          onCadastrar={(dados) => {
            onCadastrarHospital(dados);
            setHospitalParaCadastrar(null);
          }}
        />
      )}
    </div>
  );
}

// =====================================================================
// CadastroRapidoHospital — modal pra cadastrar hospital direto do import
// =====================================================================
function CadastroRapidoHospital({ abrev, familiasUsadas, onCancelar, onCadastrar }) {
  const familiasLivres = (window.FAMILIAS_HOSPITAL || []).filter(f => !familiasUsadas.includes(f.family));
  const familiaInicial = familiasLivres[0] || window.FAMILIAS_HOSPITAL?.[0];

  const [dados, setDados] = useStateImp({
    nome: '', abrev: abrev.toUpperCase(),
    endereco: '', family: familiaInicial?.family,
    turnos: {
      manha: { inicio: 7,  duracao: 6 },
      tarde: { inicio: 13, duracao: 6 },
      noite: { inicio: 19, duracao: 12 },
      noitinha: null,
    },
  });
  const familiaObj = (window.FAMILIAS_HOSPITAL || []).find(f => f.family === dados.family) || familiaInicial;

  const submit = () => {
    if (!dados.nome.trim()) return;
    const turnosLimpos = {};
    for (const k of ['manha', 'tarde', 'noitinha', 'noite']) {
      if (dados.turnos[k]) turnosLimpos[k] = dados.turnos[k];
    }
    onCadastrar({
      nome: dados.nome.trim(),
      abrev: dados.abrev.trim().toUpperCase(),
      endereco: dados.endereco.trim(),
      family: dados.family,
      cor: familiaObj.cor,
      corDeep: familiaObj.corDeep,
      corWash: familiaObj.corWash,
      deslocCasa: 30,
      turnos: turnosLimpos,
    });
  };

  const toggleTurno = (turno) => {
    const padrões = {
      manha:    { inicio: 7,  duracao: 6 },
      tarde:    { inicio: 13, duracao: 6 },
      noitinha: { inicio: 19, duracao: 5 },
      noite:    { inicio: 19, duracao: 12 },
    };
    setDados({...dados, turnos: {...dados.turnos, [turno]: dados.turnos[turno] ? null : padrões[turno]}});
  };

  const ajustarTurno = (turno, campo, valor) => {
    if (!dados.turnos[turno]) return;
    setDados({...dados, turnos: {...dados.turnos, [turno]: {...dados.turnos[turno], [campo]: parseFloat(valor) || 0}}});
  };

  return (
    <div onClick={onCancelar} style={{
      position: 'fixed', inset: 0, zIndex: 50,
      background: 'rgba(58, 46, 42, 0.4)', backdropFilter: 'blur(2px)',
      display: 'grid', placeItems: 'center', padding: 20, overflowY: 'auto',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--bg)', borderRadius: 'var(--r-lg)',
        padding: 'var(--s-6)', width: '100%', maxWidth: 520,
        maxHeight: 'calc(100vh - 40px)', overflowY: 'auto',
        boxShadow: 'var(--shadow-lg)',
      }}>
        <h2 className="h2" style={{fontSize: 24, marginTop: 0}}>Cadastrar {abrev}</h2>
        <p className="small" style={{marginTop: 4, marginBottom: 'var(--s-4)'}}>
          Preencha rapidinho — você pode refinar depois na aba Hospitais.
        </p>

        <div style={{display:'grid', gap: 'var(--s-3)'}}>
          <div>
            <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Nome</label>
            <input className="input" value={dados.nome}
              onChange={e => setDados({...dados, nome: e.target.value})}
              placeholder={`Ex.: Hospital ${abrev}`}/>
          </div>
          <div style={{display:'grid', gridTemplateColumns: '120px 1fr', gap: 'var(--s-3)'}}>
            <div>
              <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Sigla</label>
              <input className="input" value={dados.abrev}
                onChange={e => setDados({...dados, abrev: e.target.value.toUpperCase()})}/>
            </div>
            <div>
              <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Endereço</label>
              <input className="input" value={dados.endereco}
                onChange={e => setDados({...dados, endereco: e.target.value})}
                placeholder="Asa Sul, Brasília"/>
            </div>
          </div>

          <div>
            <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Cor</label>
            <div style={{display:'flex', flexWrap:'wrap', gap: 6}}>
              {(window.FAMILIAS_HOSPITAL || []).map(f => (
                <button key={f.family} type="button" onClick={() => setDados({...dados, family: f.family})}
                  style={{
                    width: 32, height: 32, borderRadius: 999,
                    border: dados.family === f.family ? '2px solid var(--ink)' : '1px solid var(--line)',
                    background: f.cor, cursor: 'pointer', padding: 0,
                  }} title={f.family}/>
              ))}
            </div>
          </div>

          <div style={{
            padding: 'var(--s-3) var(--s-4)', background: 'var(--bg-alt)',
            borderRadius: 'var(--r-md)', border: '1px solid var(--line)',
          }}>
            <label className="eyebrow" style={{display:'block', marginBottom: 8}}>Turnos padrão deste hospital</label>
            <p className="small" style={{fontSize: 11, marginTop: 0, marginBottom: 'var(--s-3)'}}>
              Define como agentes de IA traduzem "Manhã/Tarde/Noite" em horários reais ao importar escalas. Pode editar depois.
            </p>
            <div style={{display:'grid', gap: 'var(--s-2)'}}>
              {[
                {k: 'manha', l: 'Manhã'},
                {k: 'tarde', l: 'Tarde'},
                {k: 'noitinha', l: 'Noitinha'},
                {k: 'noite', l: 'Noite'},
              ].map(t => {
                const ativo = !!dados.turnos[t.k];
                return (
                  <div key={t.k} style={{
                    display: 'grid',
                    gridTemplateColumns: '24px 80px 1fr 1fr',
                    gap: 'var(--s-2)', alignItems: 'center',
                  }}>
                    <input type="checkbox" checked={ativo} onChange={() => toggleTurno(t.k)}
                      style={{accentColor: 'var(--ink)', width: 16, height: 16}}/>
                    <span style={{fontSize: 13, fontWeight: 600, color: ativo ? 'var(--ink)' : 'var(--ink-3)'}}>
                      {t.l}
                    </span>
                    <div style={{display:'flex', gap: 4, alignItems:'center'}}>
                      <span className="small" style={{fontSize: 10}}>início</span>
                      <input type="number" min="0" max="23" disabled={!ativo}
                        value={ativo ? dados.turnos[t.k].inicio : ''}
                        onChange={e => ajustarTurno(t.k, 'inicio', e.target.value)}
                        style={{
                          width: 56, padding: '4px 8px',
                          border: '1px solid var(--line)', borderRadius: 'var(--r-sm)',
                          fontFamily: 'var(--font-body)', fontSize: 12,
                          background: ativo ? 'var(--bg)' : 'var(--bg-alt)',
                        }}/>
                      <span className="small" style={{fontSize: 10}}>h</span>
                    </div>
                    <div style={{display:'flex', gap: 4, alignItems:'center'}}>
                      <span className="small" style={{fontSize: 10}}>dur.</span>
                      <input type="number" min="1" max="24" disabled={!ativo}
                        value={ativo ? dados.turnos[t.k].duracao : ''}
                        onChange={e => ajustarTurno(t.k, 'duracao', e.target.value)}
                        style={{
                          width: 56, padding: '4px 8px',
                          border: '1px solid var(--line)', borderRadius: 'var(--r-sm)',
                          fontFamily: 'var(--font-body)', fontSize: 12,
                          background: ativo ? 'var(--bg)' : 'var(--bg-alt)',
                        }}/>
                      <span className="small" style={{fontSize: 10}}>h</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div style={{display:'flex', gap: 'var(--s-2)', marginTop: 'var(--s-3)'}}>
            <button className="btn btn--ghost" onClick={onCancelar} style={{flex:1, justifyContent:'center'}}>Cancelar</button>
            <button className="btn" onClick={submit} disabled={!dados.nome.trim()}
              style={{flex:1, justifyContent:'center', background:'var(--ink)', color:'var(--bg)',
                opacity: dados.nome.trim() ? 1 : 0.5}}>
              Cadastrar e voltar
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function ImportRow({ bloco, hospitais, checked, onToggle }) {
  const b = bloco.raw;
  const ef = bloco.efetivo;
  const dia = window.diaSemanaBR(b.data);
  const ehInvalido = bloco.flags.semHospital || bloco.flags.semHorario;
  const fim = (ef.horaInicio != null && ef.duracao != null) ? (ef.horaInicio + ef.duracao) : null;
  const flags = [];
  if (bloco.flags.semHospital) flags.push({ texto: `Hospital "${b.hospitalAbrev}" não cadastrado`, severidade: 'err' });
  if (bloco.flags.semHorario) flags.push({ texto: `Hospital sem turno "${b.turno}" cadastrado`, severidade: 'err' });
  if (bloco.flags.duplicado) flags.push({ texto: 'Já existe (duplicado)', severidade: 'warn' });
  if (bloco.flags.conflito) flags.push({ texto: `Sobrepõe ${bloco.conflitos.length} bloco${bloco.conflitos.length>1?'s':''}`, severidade: 'warn' });
  if (bloco.flags.cadeia) flags.push({ texto: `Vai criar cadeia de ${Math.round(bloco.cadeia.horas)}h sem descanso`, severidade: 'err' });

  return (
    <label style={{
      display: 'grid',
      gridTemplateColumns: '24px auto 1fr auto',
      gap: 'var(--s-3)', alignItems: 'center',
      padding: 'var(--s-3) var(--s-4)',
      borderBottom: '1px solid var(--line)',
      cursor: ehInvalido ? 'not-allowed' : 'pointer',
      opacity: ehInvalido ? 0.55 : 1,
    }}>
      <input type="checkbox" checked={checked} disabled={ehInvalido} onChange={onToggle}
        style={{accentColor: 'var(--ink)', width: 16, height: 16}}/>
      <div style={{
        width: 6, height: 36, borderRadius: 3,
        background: bloco.hosp?.cor || 'var(--line-2)',
      }}/>
      <div style={{minWidth: 0}}>
        <div style={{fontWeight: 600, fontSize: 13, color: 'var(--ink)'}}>
          {bloco.hosp?.abrev || b.hospitalAbrev || '—'}
          {b.turno && (
            <span className="eyebrow" style={{marginLeft: 8, fontSize: 10}}>{b.turno}</span>
          )}
        </div>
        <div className="small" style={{fontSize: 12, color: 'var(--ink-2)', marginTop: 2}}>
          {window.DIAS_COMPLETO[dia]} {window.fmtDataCurto(b.data)}
          {fim != null
            ? ` · ${window.fmtHora(ef.horaInicio)} — ${window.fmtHora(fim)} (${ef.duracao}h)`
            : ' · horário não resolvido'}
        </div>
        {flags.length > 0 && (
          <div style={{marginTop: 4, display:'flex', flexWrap:'wrap', gap: 4}}>
            {flags.map((f, i) => (
              <span key={i} style={{
                fontSize: 10, fontWeight: 700, padding: '2px 8px',
                borderRadius: 'var(--r-pill)',
                background: f.severidade === 'err' ? 'var(--err-bg)' : 'var(--warn-bg)',
                color: f.severidade === 'err' ? 'var(--err)' : 'var(--warn)',
              }}>{f.texto}</span>
            ))}
          </div>
        )}
        {b.observacao && (
          <div className="small" style={{fontSize: 11, color: 'var(--ink-3)', marginTop: 2, fontStyle: 'italic'}}>
            {b.observacao}
          </div>
        )}
      </div>
      <div style={{
        fontFamily:'var(--font-display)', fontSize: 22, fontWeight: 400,
        color: bloco.hosp?.corDeep || 'var(--ink-3)',
      }}>
        {ef.duracao != null ? `${ef.duracao}h` : '—'}
      </div>
    </label>
  );
}

// =====================================================================
// ImportarICS — sobe arquivo .ics, mostra preview, importa como bloqueios
// =====================================================================
function ImportarICS({ onImportarICS, blocos }) {
  const [eventos, setEventos] = useStateImp(null);
  const [selecionados, setSelecionados] = useStateImp({});
  const [erro, setErro] = useStateImp(null);
  const [statusFinal, setStatusFinal] = useStateImp(null);
  const fileRef = React.useRef(null);

  const onFile = async (file) => {
    setErro(null); setStatusFinal(null);
    try {
      const txt = await file.text();
      const evs = window.parsearICS(txt);
      const candidatos = window.eventosICSParaBlocos(evs);
      if (candidatos.length === 0) {
        setErro('Nenhum evento útil encontrado neste .ics. (Eventos exportados do próprio Colo Ritmo são ignorados.)');
        return;
      }
      // Marca duplicatas com bloqueios já existentes (mesma data + horaInicio + duracao)
      const candidatosAnotados = candidatos.map(c => ({
        ...c,
        flagDup: (blocos || []).some(b =>
          b.tipo === 'bloqueio' &&
          b.data === c.bloco.data &&
          Math.abs(b.horaInicio - c.bloco.horaInicio) < 0.1 &&
          Math.abs(b.duracao - c.bloco.duracao) < 0.1
        ),
      }));
      setEventos(candidatosAnotados);
      const sel = {};
      candidatosAnotados.forEach(c => { sel[c.idx] = !c.flagDup; });
      setSelecionados(sel);
    } catch (e) {
      setErro('Falha ao ler arquivo: ' + e.message);
    }
  };

  const importar = () => {
    if (!eventos) return;
    const blocosSelecionados = eventos
      .filter(c => selecionados[c.idx])
      .map(c => c.bloco);
    onImportarICS(blocosSelecionados, 'Google Calendar (.ics)');
    setStatusFinal(`${blocosSelecionados.length} evento${blocosSelecionados.length === 1 ? '' : 's'} importado${blocosSelecionados.length === 1 ? '' : 's'} como bloqueio${blocosSelecionados.length === 1 ? '' : 's'}.`);
    setEventos(null); setSelecionados({});
    if (fileRef.current) fileRef.current.value = '';
    setTimeout(() => setStatusFinal(null), 6000);
  };

  return (
    <div style={{
      padding: 'var(--s-5)', background: 'var(--bg)',
      border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
    }}>
      <h3 className="h3" style={{margin: 0, fontSize: 18}}>Importar do calendário</h3>
      <p className="small" style={{fontSize: 12, marginTop: 4, marginBottom: 'var(--s-3)'}}>
        Sobe um arquivo <code style={{background:'var(--bg-alt)', padding:'1px 6px', borderRadius: 4}}>.ics</code> exportado
        do Google/Apple Calendar. Eventos viram bloqueios (indisponível pra plantão).
        <a href="#" onClick={e => e.preventDefault()}
          title="Google Calendar → Configurações → Importar e Exportar → Exportar"
          style={{color: 'var(--colo-blue-tag)', marginLeft: 6}}>como exportar?</a>
      </p>

      {statusFinal && (
        <div style={{
          padding: 'var(--s-3)', background: 'var(--ok-bg)', color: 'var(--ok)',
          borderRadius: 'var(--r-md)', fontSize: 13, fontWeight: 600, marginBottom: 'var(--s-3)',
        }}>{statusFinal}</div>
      )}

      <input ref={fileRef} type="file" accept=".ics,text/calendar"
        onChange={e => e.target.files?.[0] && onFile(e.target.files[0])}
        aria-label="Selecionar arquivo .ics"
        style={{
          display: 'block', width: '100%',
          padding: 'var(--s-3)',
          border: '1px dashed var(--line-2)', borderRadius: 'var(--r-md)',
          fontSize: 13, fontFamily: 'var(--font-body)',
          background: 'var(--bg-alt)', cursor: 'pointer',
        }}/>

      {erro && (
        <div style={{
          marginTop: 8, padding: 'var(--s-3)',
          background: 'var(--err-bg)', color: 'var(--err)',
          borderRadius: 'var(--r-md)', fontSize: 12, fontWeight: 600,
        }}>{erro}</div>
      )}

      {eventos && (
        <div style={{marginTop: 'var(--s-4)'}}>
          <div className="eyebrow" style={{marginBottom: 8}}>
            {eventos.length} evento{eventos.length === 1 ? '' : 's'} encontrado{eventos.length === 1 ? '' : 's'}
          </div>
          <div style={{
            border: '1px solid var(--line)', borderRadius: 'var(--r-md)',
            maxHeight: 320, overflowY: 'auto',
          }}>
            {eventos.map(c => {
              const dia = window.diaSemanaBR(c.bloco.data);
              const fim = (c.bloco.horaInicio + c.bloco.duracao);
              return (
                <label key={c.idx} style={{
                  display: 'grid', gridTemplateColumns: '24px 1fr auto',
                  gap: 'var(--s-3)', alignItems: 'center',
                  padding: 'var(--s-3) var(--s-4)',
                  borderBottom: '1px solid var(--line)',
                  cursor: 'pointer',
                }}>
                  <input type="checkbox" checked={!!selecionados[c.idx]}
                    onChange={() => setSelecionados({...selecionados, [c.idx]: !selecionados[c.idx]})}
                    style={{accentColor: 'var(--ink)', width: 16, height: 16}}/>
                  <div>
                    <div style={{fontWeight: 600, fontSize: 13}}>{c.bloco.motivo}</div>
                    <div className="small" style={{fontSize: 12, color:'var(--ink-2)', marginTop: 2}}>
                      {window.DIAS_COMPLETO[dia]} {window.fmtDataCurto(c.bloco.data)} · {window.fmtHora(c.bloco.horaInicio)} — {window.fmtHora(fim)} ({c.bloco.duracao}h)
                    </div>
                    {c.flagDup && (
                      <span style={{
                        display: 'inline-block', marginTop: 4,
                        fontSize: 10, fontWeight: 700, padding: '2px 8px',
                        borderRadius: 'var(--r-pill)',
                        background: 'var(--warn-bg)', color: 'var(--warn)',
                      }}>Já existe (duplicado)</span>
                    )}
                  </div>
                  <div style={{
                    fontFamily:'var(--font-display)', fontSize: 18,
                    color: 'var(--ink-3)',
                  }}>{c.bloco.duracao}h</div>
                </label>
              );
            })}
          </div>
          <div style={{display: 'flex', justifyContent: 'flex-end', marginTop: 'var(--s-3)'}}>
            <button onClick={importar}
              disabled={Object.values(selecionados).every(v => !v)}
              className="btn"
              style={{
                background: 'var(--ink)', color: 'var(--bg)',
                opacity: Object.values(selecionados).some(v => v) ? 1 : 0.6,
                justifyContent: 'center',
              }}>
              Importar como bloqueios
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// =====================================================================
// ExportarICS — gera .ics da agenda atual e baixa
// =====================================================================
function ExportarICS({ blocos, hospitais }) {
  const exportaveis = (blocos || []).filter(b =>
    b.tipo === 'plantao' || b.tipo === 'sono' || b.tipo === 'bloqueio'
  );

  const baixar = () => {
    const ics = window.gerarICS(blocos, hospitais);
    const blob = new Blob([ics], { type: 'text/calendar;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    const nome = `colo-ritmo-${new Date().toISOString().slice(0,10)}.ics`;
    a.href = url; a.download = nome;
    document.body.appendChild(a); a.click();
    document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  const baixarJSON = () => {
    const dados = {
      schemaVersion: 1,
      exportadoEm: new Date().toISOString(),
      blocos: blocos || [],
    };
    const blob = new Blob([JSON.stringify(dados, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `colo-ritmo-backup-${new Date().toISOString().slice(0,10)}.json`;
    document.body.appendChild(a); a.click();
    document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  return (
    <div style={{
      padding: 'var(--s-5)', background: 'var(--bg)',
      border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
    }}>
      <h3 className="h3" style={{margin: 0, fontSize: 18}}>Exportar pra calendário</h3>
      <p className="small" style={{fontSize: 12, marginTop: 4, marginBottom: 'var(--s-3)'}}>
        Baixa um <code style={{background:'var(--bg-alt)', padding:'1px 6px', borderRadius: 4}}>.ics</code> com
        seus plantões, sonos protegidos e bloqueios. Importe no Google/Apple Calendar pra ver tudo no celular,
        com notificações automáticas. Inclui {exportaveis.length} evento{exportaveis.length === 1 ? '' : 's'}.
      </p>

      <div style={{display: 'flex', gap: 'var(--s-3)', flexWrap: 'wrap'}}>
        <button onClick={baixar} disabled={exportaveis.length === 0}
          className="btn"
          style={{
            background: 'var(--ink)', color: 'var(--bg)',
            opacity: exportaveis.length > 0 ? 1 : 0.5,
            justifyContent: 'center',
          }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          Baixar .ics
        </button>
        <button onClick={baixarJSON} className="btn btn--ghost" style={{justifyContent: 'center'}}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
          Backup completo (JSON)
        </button>
      </div>

      <details style={{marginTop: 'var(--s-3)'}}>
        <summary className="small" style={{cursor: 'pointer', fontSize: 12, color: 'var(--ink-2)'}}>
          Como importar no Google Calendar
        </summary>
        <ol className="small" style={{fontSize: 12, color: 'var(--ink-2)', marginTop: 8, paddingLeft: 18, lineHeight: 1.6}}>
          <li>Acesse <strong>calendar.google.com</strong> no computador</li>
          <li>Engrenagem ⚙ → <strong>Configurações</strong> → <strong>Importar e exportar</strong></li>
          <li>Selecione o arquivo <code>.ics</code> baixado</li>
          <li>Escolha em qual calendário importar (sugestão: criar um chamado "Plantões" pra ver/ocultar com 1 clique)</li>
          <li>Importar</li>
        </ol>
        <p className="small" style={{fontSize: 11, color: 'var(--ink-3)', marginTop: 8, fontStyle: 'italic'}}>
          No iPhone: abre o <code>.ics</code> direto pelo Mail/Files → "Adicionar a Calendário". Apple Calendar puxa
          também do Google se você sincronizar a conta.
        </p>
      </details>
    </div>
  );
}

Object.assign(window, { ImportView });
