// aero-shell.jsx — Site chrome: top nav, observation ticker, footer,
// hash-based router. Exposes window.AeroShell, useRoute().

const { useState, useEffect, useMemo, useRef } = React;

// ─────────────────────────────────────────────────────────────────────
// Tokens — site-wide design system, neutral warm cream chrome.
// Page-level palettes (atmospheric, weather-driven) sit INSIDE this.
// ─────────────────────────────────────────────────────────────────────
const AERO = {
  paper: '#f3eee2',       // canvas
  paperDeep: '#e8e1cf',
  ink: '#1b1a17',
  inkDim: '#4b4940',
  inkSoft: '#7e7a6a',
  hair: 'rgba(27,26,23,0.14)',
  line: 'rgba(27,26,23,0.32)',
  accent: '#3a4f6b',
  warm: '#b86a2c',
  danger: '#a8463a',
  ok: '#5e7c4a',
};

// Inject base CSS once.
(function () {
  if (document.getElementById('aero-base')) return;
  const s = document.createElement('style');
  s.id = 'aero-base';
  s.textContent = `
    html, body { background: ${AERO.paper}; color: ${AERO.ink}; margin: 0; padding: 0; }
    body {
      font-family: 'Geist', -apple-system, system-ui, sans-serif;
      -webkit-font-smoothing: antialiased; font-feature-settings: 'ss01';
    }
    *::-webkit-scrollbar { width: 6px; height: 6px; }
    *::-webkit-scrollbar-track { background: transparent; }
    *::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.18); border-radius: 3px; }
    a { color: inherit; text-decoration: none; }
    .aero-mono { font-family: 'JetBrains Mono', ui-monospace, monospace; }
    .aero-serif { font-family: 'Instrument Serif', 'Iowan Old Style', serif; }
    .aero-eyebrow {
      font-family: 'JetBrains Mono', monospace;
      font-size: 11px; letter-spacing: 1.6px; text-transform: uppercase;
      color: ${AERO.inkSoft};
    }
    .aero-link { transition: color .15s; }
    .aero-link:hover { color: ${AERO.warm}; }
    /* selection */
    ::selection { background: ${AERO.warm}; color: ${AERO.paper}; }
  `;
  document.head.appendChild(s);
})();

// ─────────────────────────────────────────────────────────────────────
// Hash router — #/home, #/city/smr, #/radar, #/alerts, #/api
// ─────────────────────────────────────────────────────────────────────
function parseHash(h) {
  const raw = (h || "").replace(/^#\/?/, "");
  if (!raw) return { name: "home", params: {} };
  const [name, ...rest] = raw.split("/");
  return { name, params: { id: rest[0] } };
}
function useRoute() {
  const [route, setRoute] = useState(() => parseHash(window.location.hash));
  useEffect(() => {
    const onChange = () => setRoute(parseHash(window.location.hash));
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return route;
}
function navigate(path) { window.location.hash = path; }

// ─────────────────────────────────────────────────────────────────────
// Logo wordmark — bespoke, draws an isobar through the AEROGRAMA letters
// ─────────────────────────────────────────────────────────────────────
function Wordmark({ size = 22, color = AERO.ink }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 8 }}>
      <svg width="20" height="20" viewBox="0 0 20 20" style={{ verticalAlign: 'middle' }}>
        {/* concentric isobars */}
        <ellipse cx="10" cy="10" rx="8" ry="6.5" fill="none" stroke={color} strokeWidth="0.8" />
        <ellipse cx="10" cy="10" rx="5" ry="4" fill="none" stroke={color} strokeWidth="0.8" />
        <circle cx="10" cy="10" r="1.4" fill={color} />
      </svg>
      <span style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontWeight: 600, letterSpacing: 2,
        fontSize: size, color,
      }}>AEROGRAMA</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Top navigation
// ─────────────────────────────────────────────────────────────────────
function TopNav({ lang, setLang }) {
  const route = useRoute();
  const items = lang === "pt"
    ? [
      ["home", "Início"],
      ["city/smr", "Previsão"],
      ["radar", "Radar"],
      ["alerts", "Alertas"],
      ["api", "API"],
    ]
    : [
      ["home", "Home"],
      ["city/smr", "Forecast"],
      ["radar", "Radar"],
      ["alerts", "Alerts"],
      ["api", "API"],
    ];
  const active = (slug) => {
    const base = slug.split("/")[0];
    return route.name === base || (base === "home" && (route.name === "" || !route.name));
  };
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 60,
      background: `${AERO.paper}f0`,
      backdropFilter: 'blur(14px) saturate(140%)',
      WebkitBackdropFilter: 'blur(14px) saturate(140%)',
      borderBottom: `0.5px solid ${AERO.hair}`,
    }}>
      <div style={{
        maxWidth: 1320, margin: '0 auto',
        padding: '18px 36px',
        display: 'flex', alignItems: 'center', gap: 36,
      }}>
        <a href="#/home" style={{ flex: '0 0 auto' }}><Wordmark /></a>
        <nav style={{ flex: 1, display: 'flex', gap: 28 }}>
          {items.map(([slug, label]) => (
            <a key={slug} href={"#/" + slug} className="aero-link" style={{
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 11, letterSpacing: 1.8, textTransform: 'uppercase',
              color: active(slug) ? AERO.ink : AERO.inkSoft,
              fontWeight: active(slug) ? 600 : 400,
              paddingBottom: 4,
              borderBottom: active(slug) ? `1.5px solid ${AERO.ink}` : '1.5px solid transparent',
            }}>{label}</a>
          ))}
        </nav>
        <button onClick={() => setLang(lang === "pt" ? "en" : "pt")} style={{
          background: 'transparent', border: `0.5px solid ${AERO.line}`,
          borderRadius: 999, padding: '5px 12px',
          fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
          letterSpacing: 1, color: AERO.ink, cursor: 'pointer',
        }}>
          {lang === "pt" ? "PT / EN" : "EN / PT"}
        </button>
        <a href="#/api" style={{
          background: AERO.ink, color: AERO.paper,
          padding: '9px 16px', borderRadius: 999,
          fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
          letterSpacing: 1.4, textTransform: 'uppercase',
        }}>{lang === "pt" ? "Acessar API" : "Get API"}</a>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Live observation ticker — slim strip under the nav, current conditions
// at featured cities, scrolls horizontally on hover (decorative only).
// ─────────────────────────────────────────────────────────────────────
function ObservationTicker({ lang }) {
  const t = window.WX.T[lang];
  const defaultItems = [
    { city: "Santa Maria", temp: "14.4°", pt: "Garoa intensa", en: "Dense drizzle" },
    { city: "Porto Alegre", temp: "15.1°", pt: "Chuva fraca", en: "Light rain" },
    { city: "São Paulo", temp: "19.8°", pt: "Nublado", en: "Overcast" },
    { city: "Rio de Janeiro", temp: "24.6°", pt: "Parc. nublado", en: "Partly cloudy" },
    { city: "Brasília", temp: "21.2°", pt: "Quase limpo", en: "Mainly clear" },
    { city: "Manaus", temp: "28.4°", pt: "Chuva", en: "Rain" },
    { city: "Recife", temp: "27.0°", pt: "Parc. nublado", en: "Partly cloudy" },
    { city: "Lisboa", temp: "16.8°", pt: "Quase limpo", en: "Mainly clear" },
    { city: "London", temp: "9.3°", pt: "Neblina", en: "Fog" },
    { city: "Tokyo", temp: "22.1°", pt: "Limpo", en: "Clear" },
  ];

  const [items, setItems] = useState(defaultItems);

  useEffect(() => {
    let alive = true;
    const fetchTicker = async () => {
      try {
        const toFetch = window.WX.CITIES.slice(0, 10);
        // Fallback to default cities if CITIES array is short
        const results = await Promise.all(
          toFetch.map(c => window.WX.fetchWeather(c.lat, c.lon, 1).catch(() => null))
        );
        if (!alive) return;
        
        const newItems = results.map((res, i) => {
          if (!res || !res.current_complete) return defaultItems[i];
          const cur = res.current_complete;
          return {
            city: toFetch[i].name,
            temp: cur.temperature_2m.toFixed(1) + "°",
            pt: cur.weathercode_desc.pt,
            en: cur.weathercode_desc.en
          };
        });
        setItems(newItems);
      } catch (e) {
        console.error(e);
      }
    };
    fetchTicker();
    return () => { alive = false; };
  }, []);

  return (
    <div style={{
      position: 'sticky', top: 64, zIndex: 50,
      background: AERO.paperDeep,
      borderBottom: `0.5px solid ${AERO.hair}`,
      overflow: 'hidden', whiteSpace: 'nowrap',
    }}>
      <div style={{
        maxWidth: 1320, margin: '0 auto',
        padding: '7px 36px',
        display: 'flex', alignItems: 'center', gap: 18,
        fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5,
        color: AERO.inkDim, letterSpacing: 0.5,
      }}>
        <span style={{ color: AERO.danger, fontWeight: 600, letterSpacing: 1.5 }}>
          ● {lang === "pt" ? "AO VIVO" : "LIVE"}
        </span>
        <div style={{ width: 1, height: 12, background: AERO.line, opacity: 0.4 }} />
        <div style={{ flex: 1, display: 'flex', gap: 22, overflowX: 'auto', scrollbarWidth: 'none' }}>
          {items.map((it, i) => (
            <span key={i} style={{ display: 'inline-flex', gap: 8, alignItems: 'baseline', flexShrink: 0 }}>
              <span style={{ color: AERO.inkSoft, letterSpacing: 1, textTransform: 'uppercase' }}>{it.city}</span>
              <span style={{ color: AERO.ink, fontWeight: 600 }}>{it.temp}</span>
              <span style={{ color: AERO.inkSoft, opacity: 0.8 }}>{lang === "pt" ? it.pt : it.en}</span>
            </span>
          ))}
        </div>
        <span style={{ color: AERO.inkSoft, flexShrink: 0 }}>
          {lang === "pt" ? "Atualizado" : "Updated"} {new Date().toLocaleTimeString(lang === "pt" ? "pt-BR" : "en-US", { hour: '2-digit', minute: '2-digit' })} GMT-3
        </span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────────────────────────────
function Footer({ lang }) {
  const cols = lang === "pt"
    ? [
      ["Produto", ["Início", "Previsão", "Radar", "Alertas", "Estações"]],
      ["Plataforma", ["API REST", "Documentação", "Status", "Limites", "Webhooks"]],
      ["Dados", ["Fontes & licenças", "Modelos numéricos", "Estações INMET", "Imagens GOES-16", "Histórico"]],
      ["Empresa", ["Sobre", "Equipe", "Contato", "Imprensa", "Carreiras"]],
    ]
    : [
      ["Product", ["Home", "Forecast", "Radar", "Alerts", "Stations"]],
      ["Platform", ["REST API", "Documentation", "Status", "Limits", "Webhooks"]],
      ["Data", ["Sources & licenses", "Numerical models", "INMET stations", "GOES-16 imagery", "Archive"]],
      ["Company", ["About", "Team", "Contact", "Press", "Careers"]],
    ];
  return (
    <footer style={{
      background: AERO.paperDeep,
      borderTop: `0.5px solid ${AERO.hair}`,
      marginTop: 80,
    }}>
      <div style={{
        maxWidth: 1320, margin: '0 auto',
        padding: '60px 36px 32px',
      }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr repeat(4, 1fr)', gap: 40 }}>
          <div>
            <Wordmark />
            <div className="aero-serif" style={{
              fontSize: 26, fontStyle: 'italic',
              color: AERO.ink, marginTop: 14, lineHeight: 1.2,
              maxWidth: 280,
            }}>
              {lang === "pt"
                ? "Observação atmosférica em tempo real, do tropical ao subantártico."
                : "Real-time atmospheric observation, tropics to subantarctic."}
            </div>
          </div>
          {cols.map(([h, items]) => (
            <div key={h}>
              <div className="aero-eyebrow" style={{ marginBottom: 14 }}>{h}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {items.map((it, i) => (
                  <a key={i} className="aero-link" href="#" style={{
                    fontSize: 13, color: AERO.inkDim,
                  }}>{it}</a>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div style={{
          marginTop: 60, paddingTop: 22,
          borderTop: `0.5px solid ${AERO.hair}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5,
          color: AERO.inkSoft, letterSpacing: 0.5,
        }}>
          <span>© 2026 AEROGRAMA · {lang === "pt" ? "Sistema Meteorológico Delta" : "Delta Meteorological System"}</span>
          <span>
            {lang === "pt" ? "Fontes" : "Sources"}: INMET · CPTEC · DHN · ECMWF · NOAA · EUMETSAT
          </span>
          <span>
            {lang === "pt" ? "Latência" : "Latency"} 0.3s · 99.97% uptime
          </span>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Page Shell — wraps the active page with chrome
// ─────────────────────────────────────────────────────────────────────
function AeroShell({ children, lang, setLang }) {
  return (
    <div style={{ minHeight: '100vh', background: AERO.paper }}>
      <TopNav lang={lang} setLang={setLang} />
      <ObservationTicker lang={lang} />
      <main>{children}</main>
      <Footer lang={lang} />
      <CookieConsent lang={lang} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Common building blocks
// ─────────────────────────────────────────────────────────────────────
function Container({ children, style = {} }) {
  return (
    <div style={{ maxWidth: 1320, margin: '0 auto', padding: '0 36px', ...style }}>{children}</div>
  );
}

function SectionEyebrow({ children, hint }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      borderTop: `1px solid ${AERO.line}`, paddingTop: 14, marginBottom: 22,
    }}>
      <div className="aero-eyebrow" style={{ color: AERO.ink, fontWeight: 600 }}>{children}</div>
      {hint && <div className="aero-eyebrow" style={{ color: AERO.inkSoft, fontWeight: 400 }}>{hint}</div>}
    </div>
  );
}

function TinyChart({ values, width, height, color, fill, smooth = true, strokeWidth = 1.5 }) {
  // re-uses Sparkline from weather-vis.jsx
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block' }}>
      <Sparkline values={values} width={width} height={height} color={color}
        fill={fill} smooth={smooth} strokeWidth={strokeWidth} />
    </svg>
  );
}

function CookieConsent({ lang }) {
  const [show, setShow] = useState(false);

  useEffect(() => {
    if (!localStorage.getItem('aerograma_consent')) {
      setShow(true);
    }
  }, []);

  const handleAccept = () => {
    localStorage.setItem('aerograma_consent', 'granted');
    setShow(false);
    window.dispatchEvent(new Event('aerograma_consent_granted'));
  };

  const handleDecline = () => {
    localStorage.setItem('aerograma_consent', 'denied');
    setShow(false);
  };

  if (!show) return null;

  return (
    <div style={{
      position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
      background: AERO.ink, color: AERO.paper, padding: '16px 24px',
      borderRadius: 8, zIndex: 9999, display: 'flex', gap: 24, alignItems: 'center',
      boxShadow: '0 8px 32px rgba(0,0,0,0.2)', width: 'max-content', maxWidth: '90vw'
    }}>
      <div style={{ fontSize: 13, lineHeight: 1.5 }}>
        {lang === 'pt' 
          ? "Usamos cookies e localização para personalizar a previsão do tempo para a sua região." 
          : "We use cookies and location to personalize the weather forecast for your area."}
      </div>
      <div style={{ display: 'flex', gap: 12 }}>
        <button onClick={handleDecline} style={{
          background: 'transparent', border: `1px solid ${AERO.line}`, color: AERO.paper,
          padding: '6px 14px', borderRadius: 16, cursor: 'pointer', fontFamily: "'JetBrains Mono', monospace", fontSize: 11
        }}>
          {lang === 'pt' ? 'Recusar' : 'Decline'}
        </button>
        <button onClick={handleAccept} style={{
          background: AERO.warm, border: 'none', color: '#fff',
          padding: '6px 14px', borderRadius: 16, cursor: 'pointer', fontFamily: "'JetBrains Mono', monospace", fontSize: 11
        }}>
          {lang === 'pt' ? 'Aceitar' : 'Accept'}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, {
  AERO, AeroShell, TopNav, ObservationTicker, Footer, Wordmark,
  Container, SectionEyebrow, TinyChart, CookieConsent, useRoute, navigate,
});
