// unidade-context.jsx — Context React com o estado da unidade carregada via API.
// Expõe UnidadeProvider, useUnidade(), LoadingScreen, ErrorScreen, NotFoundScreen.

const UnidadeContext = React.createContext(null);

function useUnidade() {
  const ctx = React.useContext(UnidadeContext);
  if (!ctx) throw new Error('useUnidade fora do UnidadeProvider');
  return ctx;
}

function UnidadeProvider({ children }) {
  const [state, setState] = React.useState({ status: 'loading', unidade: null, error: null });
  const [tentativa, setTentativa] = React.useState(0);

  React.useEffect(() => {
    let cancelado = false;
    setState({ status: 'loading', unidade: null, error: null });
    const slug = window.franqueadoService.obterSlugDaURL();
    window.franqueadoService.obterPorSlug(slug)
      .then(unidade => {
        if (cancelado) return;
        setState({ status: 'ready', unidade, error: null });
        // Atualiza title e meta description com nome da unidade
        document.title = `${unidade.nomeCompleto} — Venda seu carro em até 20 minutos`;
        const meta = document.querySelector('meta[name="description"]');
        if (meta) meta.setAttribute('content', `Avaliação gratuita, sem burocracia. Venda seu carro em até 20 minutos com a ${unidade.nomeCompleto}.`);
        // Injeta o GTM dinâmico da franquia (codigoGtm vem da API).
        injetarGtm(unidade.codigoGtm);
      })
      .catch(err => {
        if (cancelado) return;
        if (err && err.status === 404) {
          setState({ status: 'notfound', unidade: null, error: err });
        } else {
          setState({ status: 'error', unidade: null, error: err });
        }
      });
    return () => { cancelado = true; };
  }, [tentativa]);

  const retry = React.useCallback(() => setTentativa(t => t + 1), []);

  if (state.status === 'loading') return <LoadingScreen />;
  if (state.status === 'error') return <ErrorScreen onRetry={retry} />;
  if (state.status === 'notfound') return <NotFoundScreen />;

  return (
    <UnidadeContext.Provider value={{ unidade: state.unidade }}>
      {children}
    </UnidadeContext.Provider>
  );
}

// ─── GTM dinâmico da franquia ────────────────────────────────────────
// O GTM fixo da franqueadora já é carregado estaticamente no head do HTML.
// Aqui injetamos o segundo container, específico desta unidade, lendo o
// campo `codigoGtm` da API. Idempotente: não injeta duas vezes o mesmo ID.
const _gtmsInjetados = new Set();
function injetarGtm(gtmId) {
  if (!gtmId) return;
  // Ignora placeholders dos mocks para não estourar 404 na preview
  if (/^GTM-XXX/.test(gtmId)) return;
  if (_gtmsInjetados.has(gtmId)) return;
  _gtmsInjetados.add(gtmId);

  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });

  const script = document.createElement('script');
  script.async = true;
  script.src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(gtmId)}`;
  document.head.appendChild(script);

  const noscript = document.createElement('noscript');
  noscript.innerHTML = `<iframe src="https://www.googletagmanager.com/ns.html?id=${encodeURIComponent(gtmId)}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
  document.body.insertBefore(noscript, document.body.firstChild);
}

// ─── Loading ─────────────────────────────────────────────────────────
function LoadingScreen() {
  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: '#fff', flexDirection: 'column', gap: 16,
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: '50%',
        border: '3px solid #F0F0F0', borderTopColor: '#E31018',
        animation: 'spin 700ms linear infinite',
      }} />
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      <span style={{ fontFamily: "'Roboto',sans-serif", fontSize: 13, color: '#919191' }}>
        Carregando unidade...
      </span>
    </div>
  );
}

// ─── Erro de rede ────────────────────────────────────────────────────
function ErrorScreen({ onRetry }) {
  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: '#F9F9F9', padding: 24,
    }}>
      <div style={{
        background: '#fff', borderRadius: 16, padding: '40px 36px', maxWidth: 440, textAlign: 'center',
        boxShadow: '0 12px 32px rgba(0,0,0,0.06)',
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: '50%', background: 'rgba(227,16,24,0.08)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18,
        }}>
          <Icon name="close" size={28} color="#E31018" stroke={2.2} />
        </div>
        <h2 style={{ fontFamily: "'Roboto',sans-serif", fontWeight: 500, fontSize: 22, color: '#2D2D2D', marginBottom: 8 }}>
          Não conseguimos carregar a unidade
        </h2>
        <p style={{ fontFamily: "'Roboto',sans-serif", fontSize: 14, color: '#5B5B5B', lineHeight: 1.6, marginBottom: 22 }}>
          Verifique sua conexão e tente novamente. Se o problema persistir, fale com a gente pelo WhatsApp.
        </p>
        <button onClick={onRetry} style={{
          padding: '12px 28px', borderRadius: 999, background: '#E31018',
          color: '#fff', border: 'none', fontFamily: "'Roboto',sans-serif",
          fontSize: 14, fontWeight: 500, cursor: 'pointer',
        }}>Tentar novamente</button>
      </div>
    </div>
  );
}

// ─── 404 / unidade não existe ────────────────────────────────────────
// Em produção: window.location.href = '/'.  Aqui mostramos a "matriz" inline
// com formulário genérico (sem filialId) e CTA WhatsApp central.
function NotFoundScreen() {
  const [nome, setNome] = React.useState('');
  const [tel, setTel] = React.useState('');
  const [cidade, setCidade] = React.useState('');
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);

  const submit = () => {
    const e = {};
    if (!nome.trim()) e.nome = 'Informe seu nome';
    if (digits(tel).length !== 11) e.tel = 'Telefone inválido';
    if (!cidade.trim()) e.cidade = 'Informe sua cidade';
    setErrors(e);
    if (Object.keys(e).length) return;
    setSent(true);
  };

  return (
    <div style={{ minHeight: '100vh', background: '#F9F9F9' }}>
      <div style={{
        background: '#fff', padding: '18px clamp(20px, 6vw, 80px)',
        borderBottom: '1px solid #E0E0E0', display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <img src="assets/logo-carflix-color.png" alt="Carflix" style={{ height: 30 }} />
        <span style={{
          fontFamily: "'Roboto',sans-serif", fontSize: 12, color: '#919191',
          borderLeft: '1px solid #E0E0E0', paddingLeft: 14,
        }}>Rede de unidades · Brasil</span>
      </div>
      <div style={{ maxWidth: 820, margin: '0 auto', padding: '64px clamp(20px, 6vw, 40px)' }}>
        <div style={{
          background: 'rgba(227,16,24,0.06)', color: '#E31018',
          display: 'inline-block', padding: '5px 14px', borderRadius: 999,
          fontFamily: "'Roboto',sans-serif", fontSize: 12, fontWeight: 500,
          textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 14,
        }}>Unidade não encontrada</div>
        <h1 style={{ fontFamily: "'Roboto',sans-serif", fontWeight: 400, fontSize: 'clamp(28px, 4vw, 40px)', color: '#2D2D2D', lineHeight: 1.2, marginBottom: 14 }}>
          Não localizamos essa unidade,<br />
          mas <span style={{ color: '#E31018', fontWeight: 500 }}>a Carflix te atende</span>.
        </h1>
        <p style={{ fontFamily: "'Roboto',sans-serif", fontSize: 16, color: '#5B5B5B', lineHeight: 1.6, marginBottom: 36, maxWidth: 560 }}>
          Deixe seus dados que vamos te conectar com a unidade Carflix mais próxima de você.
        </p>

        <div style={{
          background: '#fff', borderRadius: 16, padding: 28,
          boxShadow: '0 12px 32px rgba(0,0,0,0.06), 0 0 0 1px rgba(0,0,0,0.04)',
          maxWidth: 520,
        }}>
          {sent ? (
            <div style={{ textAlign: 'center', padding: '14px 4px' }}>
              <div style={{
                width: 56, height: 56, borderRadius: '50%', background: 'rgba(12,113,16,0.1)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16,
              }}>
                <Icon name="check" size={28} color="#0C7110" stroke={3} />
              </div>
              <h3 style={{ fontFamily: "'Roboto',sans-serif", fontWeight: 500, fontSize: 20, color: '#2D2D2D', marginBottom: 6 }}>
                Recebemos seus dados!
              </h3>
              <p style={{ fontFamily: "'Roboto',sans-serif", fontSize: 14, color: '#5B5B5B', lineHeight: 1.6 }}>
                Em breve a unidade Carflix mais próxima de {cidade} entrará em contato.
              </p>
            </div>
          ) : (
            <>
              <h2 style={{ fontFamily: "'Roboto',sans-serif", fontWeight: 500, fontSize: 18, color: '#2D2D2D', marginBottom: 16 }}>
                Encontre a unidade mais próxima
              </h2>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <Field label="Nome completo" required error={errors.nome}>
                  <input value={nome} onChange={e => setNome(e.target.value)} placeholder="Seu nome" style={inputStyle(errors.nome)} />
                </Field>
                <Field label="Telefone / WhatsApp" required error={errors.tel}>
                  <input value={tel} onChange={e => setTel(maskPhone(e.target.value))} placeholder="(11) 99999-9999" style={inputStyle(errors.tel)} inputMode="numeric" />
                </Field>
                <Field label="Cidade" required error={errors.cidade}>
                  <input value={cidade} onChange={e => setCidade(e.target.value)} placeholder="Ex: São Paulo, Campinas..." style={inputStyle(errors.cidade)} />
                </Field>
              </div>
              <button onClick={submit} style={{
                width: '100%', marginTop: 18, padding: '13px 20px', borderRadius: 8,
                background: '#E31018', color: '#fff', border: 'none',
                fontFamily: "'Roboto',sans-serif", fontSize: 15, fontWeight: 500, cursor: 'pointer',
                boxShadow: '0 4px 8.9px rgba(227,16,24,0.25)',
              }}>Quero ser contatado</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { UnidadeProvider, useUnidade });
