/* global React, ReactDOM */
const { useEffect, useState } = React;

const DEMO_CREDENTIALS = { email: "diego@cinfra.cl", password: "cinfra2025" };

function LoginModal({ onClose, onSuccess }) {
  const [email, setEmail]       = useState("");
  const [password, setPassword] = useState("");
  const [error, setError]       = useState("");
  const [loading, setLoading]   = useState(false);

  const submit = (e) => {
    e.preventDefault();
    setLoading(true);
    setTimeout(() => {
      if (email === DEMO_CREDENTIALS.email && password === DEMO_CREDENTIALS.password) {
        onSuccess();
      } else {
        setError("Credenciales incorrectas.");
        setLoading(false);
      }
    }, 600);
  };

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(22,58,67,0.45)", backdropFilter: "blur(6px)",
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        position: "relative",
        background: "var(--paper)", borderRadius: 16,
        padding: "48px 44px", width: "100%", maxWidth: 420,
        boxShadow: "0 32px 80px rgba(22,58,67,0.22)",
      }}>
        <div style={{ marginBottom: 32 }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Portal Empresa</div>
          <h2 className="serif" style={{ margin: 0, fontSize: 36, fontWeight: 400, letterSpacing: "-0.02em" }}>
            Sign In
          </h2>
        </div>
        <form onSubmit={submit} style={{ display: "grid", gap: 16 }}>
          <label style={{ display: "grid", gap: 6 }}>
            <span style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-55)", fontWeight: 500 }}>Email</span>
            <input
              type="email" value={email} onChange={e => { setEmail(e.target.value); setError(""); }}
              placeholder="tu@cinfra.cl" required autoFocus
              style={{
                border: "1px solid var(--ink-12)", borderRadius: 8,
                padding: "11px 14px", fontSize: 14, fontFamily: "inherit",
                background: "#fff", color: "var(--ink)", outline: "none",
                transition: "border-color .2s",
              }}
              onFocus={e => e.target.style.borderColor = "var(--ink)"}
              onBlur={e => e.target.style.borderColor = "var(--ink-12)"}
            />
          </label>
          <label style={{ display: "grid", gap: 6 }}>
            <span style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-55)", fontWeight: 500 }}>Contraseña</span>
            <input
              type="password" value={password} onChange={e => { setPassword(e.target.value); setError(""); }}
              placeholder="••••••••" required
              style={{
                border: "1px solid var(--ink-12)", borderRadius: 8,
                padding: "11px 14px", fontSize: 14, fontFamily: "inherit",
                background: "#fff", color: "var(--ink)", outline: "none",
                transition: "border-color .2s",
              }}
              onFocus={e => e.target.style.borderColor = "var(--ink)"}
              onBlur={e => e.target.style.borderColor = "var(--ink-12)"}
            />
          </label>
          {error && (
            <div style={{ fontSize: 13, color: "#c0392b", padding: "8px 12px", background: "rgba(192,57,43,0.07)", borderRadius: 6 }}>
              {error}
            </div>
          )}
          <button type="submit" disabled={loading} style={{
            marginTop: 8, padding: "13px", borderRadius: 8, border: 0,
            background: "var(--ink)", color: "#fff", fontSize: 13,
            letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 500,
            fontFamily: "inherit", cursor: loading ? "default" : "pointer",
            opacity: loading ? 0.7 : 1, transition: "opacity .2s",
          }}>
            {loading ? "Verificando…" : "Ingresar"}
          </button>
        </form>
        <button onClick={onClose} style={{
          position: "absolute", top: 20, right: 20,
          background: "none", border: "none", cursor: "pointer",
          fontSize: 20, color: "var(--ink-55)", lineHeight: 1,
        }}>×</button>
      </div>
    </div>
  );
}

const PROJECTS = [
  {
    name: "Rinconada",
    jefeProyecto: "Osvaldo Barrueto",
    region: "Biobío",
    tipo: "Eólico",
    mw: "260,4 MW",
    status: "Near-RTB",
    pct: 55,
    alert: true,
    kpis: [
      { label: "Capacidad", value: "260,4 MW" },
      { label: "Producción P50", value: "848,2 GWh/año" },
      { label: "Factor planta", value: "37,2%" },
      { label: "Contrato total", value: "$26,25M" },
      { label: "Pagado", value: "~$3,97M" },
      { label: "Precio/MW", value: "$105K USD" },
    ],
    tecnologia: "42 × Vestas V162-6.2 MW · Hub 145 m",
    produccion: "848,2 GWh/año P50",
    factorPlanta: "37,2%",
    cronograma: [
      { hito: "RCA", fecha: "Jul 2025", done: false },
      { hito: "RTB", fecha: "Dic 2026", done: false },
      { hito: "Concesión eléctrica", fecha: "Ene 2027", done: false },
      { hito: "COD", fecha: "Ene 2029", done: false },
    ],
    contrato: "$105K USD/MW · Total $26,25M · Pagado ~$3,97M",
    territorio: "13/14 contratos parque · LTAT 7/17 predios — rezagada",
    alertaTexto: "Fehaciencia SEN pendiente — cuello de botella. AES ejerció put option; negociaciones activas sobre titularidad.",
  },
  {
    name: "Entre Cerros",
    jefeProyecto: "Osvaldo Barrueto",
    region: "Ñuble",
    tipo: "Eólico",
    mw: "72 MW",
    status: "RTB Full ✓",
    pct: 75,
    alert: true,
    kpis: [
      { label: "Capacidad", value: "72 MW" },
      { label: "Producción P50", value: "195,5 GWh/año" },
      { label: "Factor planta", value: "31,0%" },
      { label: "Contrato total", value: "$6,97M" },
      { label: "Pagado", value: "$3,38M" },
      { label: "Predios LTAT", value: "30/30 ✓" },
    ],
    tecnologia: "10 × Goldwind GW170-7.2 MW · Hub 105 m",
    produccion: "195,5 GWh/año P50",
    factorPlanta: "31,0%",
    cronograma: [
      { hito: "RCA", fecha: "Ago 2022", done: true },
      { hito: "Conexión", fecha: "Ago 2023", done: true },
      { hito: "Concesión", fecha: "Oct 2024", done: true },
      { hito: "RTB", fecha: "Dic 2025", done: true },
      { hito: "COD", fecha: "Dic 2027", done: false },
    ],
    contrato: "Precio fijo $6,97M · Pagado $3,38M",
    territorio: "30/30 predios LTAT asegurados — cartera más completa",
    alertaTexto: "ENGIE ejerció put option; negociaciones en curso — mismo patrón que Rinconada.",
  },
  {
    name: "Vientos del Pacífico",
    jefeProyecto: "Christian Pichard",
    region: "Biobío",
    tipo: "Eólico",
    mw: "100 MW",
    status: "Permisos completos",
    pct: 30,
    alert: false,
    kpis: [
      { label: "Capacidad", value: "100 MW" },
      { label: "Producción P50", value: "~395–401 GWh/año" },
      { label: "Factor planta", value: "31,8%" },
      { label: "Contrato total", value: "$7,92M" },
      { label: "Pagado", value: "$792K" },
      { label: "Predios LTAT", value: "0/18" },
    ],
    tecnologia: "17 × Vestas V162-6.2 MW · Hub 160 m",
    produccion: "~395–401 GWh/año P50",
    factorPlanta: "31,8%",
    cronograma: [
      { hito: "Concesión", fecha: "Mar 2022", done: true },
      { hito: "RCA", fecha: "Jul 2023", done: true },
      { hito: "Conexión", fecha: "Nov 2023", done: true },
      { hito: "RTB", fecha: "Ago 2027", done: false },
      { hito: "COD", fecha: "Oct 2029", done: false },
    ],
    contrato: "$80K USD/MW · Total $7,92M · Pagado $792K",
    territorio: "LTAT 0/18 predios — servidumbres completamente pendientes. Baja urgencia.",
    alertaTexto: null,
  },
  {
    name: "Pilcomayo (Uribe Solar)",
    jefeProyecto: "Christian Pichard",
    region: "Antofagasta",
    tipo: "Solar FV",
    mw: "57,6 MWp",
    status: "Operacional — en venta",
    pct: 90,
    alert: true,
    kpis: [
      { label: "Capacidad", value: "57,6 MWp" },
      { label: "Producción 2024", value: "~146 GWh" },
      { label: "Factor planta", value: "~29%" },
      { label: "Deuda total", value: "~USD 60M" },
      { label: "Equity (dic-2024)", value: "-$9,85M" },
      { label: "Curtailment actual", value: "~16%" },
    ],
    tecnologia: "185.880 módulos Trina 310Wp · 296 trackers · BESS I: 2,5 MW / 4,2 MWh",
    produccion: "~146 GWh/año (2024)",
    factorPlanta: "~29% (ajustado curtailment)",
    cronograma: [
      { hito: "COD", fecha: "2017", done: true },
      { hito: "BESS Fase I", fecha: "Operativa", done: true },
      { hito: "BESS Fase II", fecha: "Pendiente ($30,4M)", done: false },
      { hito: "Cierre venta", fecha: "En curso", done: false },
    ],
    contrato: "Deuda: ~USD 60M (50% B. Security / 50% B. Consorcio) · Equity: -$9,85M (dic-2024)",
    territorio: "Curtailment: 27% peak 2024 → ~16% actual → <10% proyectado (línea Kimal–Lo Aguirre)",
    alertaTexto: "Asset en distress financiero. Ingresos caídos de $8M (2021) a $1,8M (2024). Compra implica asumir deuda $60M + financiar BESS II. Due diligence profundo requerido.",
  },
];

function StatusBadge({ status, alert }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5,
      fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 600,
      padding: "4px 10px", borderRadius: 999,
      background: alert ? "rgba(180,60,40,0.08)" : "rgba(22,58,67,0.07)",
      color: alert ? "#b43c28" : "var(--ink)",
    }}>
      {alert && <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#b43c28", display: "inline-block" }} />}
      {status}
    </span>
  );
}

function ProjectCard({ p, onSelect }) {
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={() => onSelect(p)}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        width: "100%", background: hover ? "#fafaf8" : "#fff",
        borderRadius: 14, border: `1px solid ${p.alert ? "rgba(180,60,40,0.15)" : "var(--ink-08)"}`,
        cursor: "pointer", fontFamily: "inherit", textAlign: "left",
        padding: "24px 28px",
        display: "grid", gridTemplateColumns: "1fr auto auto auto",
        alignItems: "center", gap: 24,
        transition: "background .15s, box-shadow .15s",
        boxShadow: hover ? "0 4px 20px rgba(22,58,67,0.07)" : "none",
      }}
    >
      <div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 4 }}>
          <span className="serif" style={{ fontSize: 22, fontWeight: 400, letterSpacing: "-0.01em" }}>{p.name}</span>
          <span style={{ fontSize: 12, color: "var(--ink-55)" }}>{p.region}</span>
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-65)" }}>{p.tipo} · {p.mw}</div>
        <div style={{ marginTop: 6, fontSize: 11, color: "var(--ink-55)" }}>
          <span style={{ letterSpacing: "0.12em", textTransform: "uppercase", fontSize: 10, color: "var(--ink)" }}>PM</span>
          {" "}<span style={{ color: "var(--ink)", fontWeight: 500 }}>{p.jefeProyecto}</span>
        </div>
      </div>
      <StatusBadge status={p.status} alert={p.alert} />
      <div style={{ textAlign: "right", minWidth: 120 }}>
        <div style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 6 }}>Avance</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ width: 80, height: 3, background: "var(--ink-08)", borderRadius: 2 }}>
            <div style={{ width: `${p.pct}%`, height: "100%", background: p.alert ? "#b43c28" : "var(--ink)", borderRadius: 2 }} />
          </div>
          <span style={{ fontSize: 12, color: "var(--ink-65)" }}>{p.pct}%</span>
        </div>
      </div>
      <span style={{ fontSize: 16, color: "var(--ink-55)", lineHeight: 1 }}>→</span>
    </button>
  );
}

function ProjectPage({ p, onBack }) {
  return (
    <div style={{ minHeight: "100vh", background: "var(--cream)", fontFamily: "var(--sans)" }}>
      {/* Top bar */}
      <div style={{
        background: "var(--ink)", color: "#fff",
        padding: "0 40px", display: "flex", alignItems: "center",
        justifyContent: "space-between", height: 60,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span className="serif" style={{ fontSize: 20, letterSpacing: "0.06em" }}>CINFRA</span>
          <span style={{ opacity: 0.35, fontSize: 14 }}>|</span>
          <span style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", opacity: 0.65 }}>Portal Empresa</span>
        </div>
        <button onClick={onBack} style={{
          display: "flex", alignItems: "center", gap: 8,
          background: "rgba(255,255,255,0.12)", border: "1px solid rgba(255,255,255,0.2)",
          color: "#fff", borderRadius: 6, padding: "6px 16px",
          fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
          fontFamily: "inherit", cursor: "pointer",
        }}>← Dashboard</button>
      </div>

      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "48px 40px" }}>

        {/* Project header */}
        <div style={{ marginBottom: 40, paddingBottom: 32, borderBottom: "1px solid var(--ink-08)" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>{p.tipo} · {p.region}</div>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 24 }}>
            <h1 className="serif" style={{ margin: 0, fontSize: 52, fontWeight: 400, letterSpacing: "-0.025em", lineHeight: 1 }}>
              {p.name}
            </h1>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 12 }}>
              <StatusBadge status={p.status} alert={p.alert} />
              <div style={{
                display: "flex", alignItems: "center", gap: 12,
                background: "#fff", border: "1px solid var(--ink-08)",
                borderRadius: 10, padding: "10px 16px",
              }}>
                <div style={{
                  width: 34, height: 34, borderRadius: "50%",
                  background: "var(--ink)", color: "#fff",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 13, fontWeight: 600, letterSpacing: "0.04em", flexShrink: 0,
                }}>
                  {p.jefeProyecto.split(" ").map(w => w[0]).join("").slice(0, 2)}
                </div>
                <div>
                  <div style={{ fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink)", marginBottom: 2 }}>Project Manager</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-2)" }}>{p.jefeProyecto}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Alert */}
        {p.alertaTexto && (
          <div style={{
            background: "rgba(180,60,40,0.06)", border: "1px solid rgba(180,60,40,0.18)",
            borderRadius: 10, padding: "16px 20px", marginBottom: 36,
            fontSize: 13, color: "#8b2e1a", lineHeight: 1.65,
          }}>
            <strong style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", display: "block", marginBottom: 6 }}>⚠ Alerta crítica</strong>
            {p.alertaTexto}
          </div>
        )}

        {/* KPI grid */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 16, marginBottom: 40 }}>
          {p.kpis.map(k => (
            <div key={k.label} style={{
              background: "#fff", borderRadius: 12, padding: "20px 20px",
              border: "1px solid var(--ink-08)",
            }}>
              <div style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 8 }}>{k.label}</div>
              <div className="serif" style={{ fontSize: 22, letterSpacing: "-0.01em", lineHeight: 1.1 }}>{k.value}</div>
            </div>
          ))}
        </div>

        {/* Main content: milestones + details */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>

          {/* Milestones timeline */}
          <div style={{ background: "#fff", borderRadius: 14, border: "1px solid var(--ink-08)", padding: "28px 32px" }}>
            <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 28, fontWeight: 500 }}>Hitos</div>
            <div style={{ position: "relative" }}>
              {/* vertical line */}
              <div style={{
                position: "absolute", left: 7, top: 8, bottom: 8,
                width: 1, background: "var(--ink-08)",
              }} />
              {p.cronograma.map((c, i) => (
                <div key={c.hito} style={{ display: "flex", alignItems: "flex-start", gap: 20, marginBottom: i < p.cronograma.length - 1 ? 28 : 0, position: "relative" }}>
                  <div style={{
                    width: 15, height: 15, borderRadius: "50%", flexShrink: 0, marginTop: 1,
                    background: c.done ? "var(--ink)" : "#fff",
                    border: `2px solid ${c.done ? "var(--ink)" : "var(--ink-12)"}`,
                    zIndex: 1,
                  }} />
                  <div style={{ flex: 1, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <span style={{ fontSize: 13, color: c.done ? "var(--ink)" : "var(--ink-65)", fontWeight: c.done ? 500 : 400 }}>{c.hito}</span>
                    <span style={{ fontSize: 12, color: c.done ? "var(--ink-55)" : "var(--ink-65)", fontStyle: c.done ? "normal" : "normal" }}>{c.fecha}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Details */}
          <div style={{ display: "grid", gap: 20 }}>
            {/* Tecnología */}
            <div style={{ background: "#fff", borderRadius: 14, border: "1px solid var(--ink-08)", padding: "24px 28px" }}>
              <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 12, fontWeight: 500 }}>Tecnología</div>
              <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6, color: "var(--ink)" }}>{p.tecnologia}</p>
            </div>

            {/* Contrato */}
            <div style={{ background: "#fff", borderRadius: 14, border: "1px solid var(--ink-08)", padding: "24px 28px" }}>
              <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 12, fontWeight: 500 }}>Contrato</div>
              <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6, color: "var(--ink)" }}>{p.contrato}</p>
            </div>

            {/* Territorio */}
            <div style={{ background: "#fff", borderRadius: 14, border: "1px solid var(--ink-08)", padding: "24px 28px" }}>
              <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 12, fontWeight: 500 }}>Territorio</div>
              <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6, color: "var(--ink)" }}>{p.territorio}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Row({ label, value }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ink)" }}>{value}</div>
    </div>
  );
}

function Dashboard({ onSignOut }) {
  const [selected, setSelected] = useState(null);

  if (selected) return <ProjectPage p={selected} onBack={() => setSelected(null)} />;

  const stats = [
    { label: "Proyectos cartera",  value: "4" },
    { label: "Capacidad total",    value: "490 MW" },
    { label: "Producción P50",     value: "~1.587 GWh" },
    { label: "Alertas activas",    value: "3" },
  ];

  return (
    <div style={{ minHeight: "100vh", background: "var(--cream)", fontFamily: "var(--sans)" }}>
      {/* Top bar */}
      <div style={{
        background: "var(--ink)", color: "#fff",
        padding: "0 40px", display: "flex", alignItems: "center",
        justifyContent: "space-between", height: 60,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span className="serif" style={{ fontSize: 20, letterSpacing: "0.06em" }}>CINFRA</span>
          <span style={{ opacity: 0.35, fontSize: 14 }}>|</span>
          <span style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", opacity: 0.65 }}>Portal Empresa</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
          <span style={{ fontSize: 12, opacity: 0.65 }}>diego@cinfra.cl</span>
          <button onClick={onSignOut} style={{
            background: "rgba(255,255,255,0.12)", border: "1px solid rgba(255,255,255,0.2)",
            color: "#fff", borderRadius: 6, padding: "6px 14px",
            fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
            fontFamily: "inherit", cursor: "pointer",
          }}>Sign Out</button>
        </div>
      </div>

      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "48px 40px" }}>
        <div style={{ marginBottom: 40 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Bienvenido</div>
          <h1 className="serif" style={{ margin: 0, fontSize: 42, fontWeight: 400, letterSpacing: "-0.02em" }}>
            Dashboard
          </h1>
        </div>

        {/* Stats */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20, marginBottom: 40 }}>
          {stats.map(s => (
            <div key={s.label} style={{
              background: "#fff", borderRadius: 12, padding: "24px 28px",
              border: "1px solid var(--ink-08)",
            }}>
              <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-55)", marginBottom: 10 }}>{s.label}</div>
              <div className="serif" style={{ fontSize: 36, letterSpacing: "-0.02em" }}>{s.value}</div>
            </div>
          ))}
        </div>

        {/* Project fichas */}
        <div style={{ marginBottom: 16 }}>
          <span style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 500, color: "var(--ink-55)" }}>
            Portafolio de Proyectos
          </span>
        </div>
        <div style={{ display: "grid", gap: 12 }}>
          {PROJECTS.map(p => <ProjectCard key={p.name} p={p} onSelect={setSelected} />)}
        </div>
      </div>
    </div>
  );
}

function App() {
  const [tweaks, setTweaks] = useState(window.__TWEAKS);

  // reveal observer
  useEffect(() => {
    const els = document.querySelectorAll(".reveal, .split-word");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });

  // texture body class
  useEffect(() => {
    document.body.classList.toggle("grain", tweaks.texture === "grain");
    document.body.classList.toggle("paper", tweaks.texture === "paper");
  }, [tweaks.texture]);

  // --- Tweak bridge ---
  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setEdit(true);
      if (e.data.type === "__deactivate_edit_mode") setEdit(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const [edit, setEdit] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [authed, setAuthed] = useState(false);

  const update = (patch) => {
    const next = { ...tweaks, ...patch };
    setTweaks(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
  };

  if (authed) return <Dashboard onSignOut={() => setAuthed(false)} />;

  return (
    <>
      <Nav onSignIn={() => setShowLogin(true)} />
      <Hero treatment={tweaks.heroTreatment} />
      {tweaks.focusLayout === "grid" ? <FocusGrid /> : <FocusEditorial />}
      <Sectores imageryOn={tweaks.imagery === "on"} />
      <Vision />
      <Closing alternation={tweaks.alternation} />

      {edit && <TweaksPanel tweaks={tweaks} update={update} />}
      {showLogin && (
        <LoginModal
          onClose={() => setShowLogin(false)}
          onSuccess={() => { setShowLogin(false); setAuthed(true); }}
        />
      )}
    </>
  );
}

function TweaksPanel({ tweaks, update }) {
  const Row = ({ label, value, options, onChange }) => (
    <div style={{ display: "grid", gap: 8 }}>
      <div style={{
        fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
        color: "rgba(255,255,255,0.55)", fontWeight: 500,
      }}>{label}</div>
      <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
        {options.map((o) => (
          <button key={o.v} onClick={() => onChange(o.v)} style={{
            padding: "7px 11px", borderRadius: 6,
            border: "1px solid rgba(255,255,255,0.18)",
            background: value === o.v ? "#fff" : "transparent",
            color: value === o.v ? "var(--ink)" : "#fff",
            fontSize: 11, letterSpacing: "0.04em",
            cursor: "pointer", fontFamily: "inherit",
            transition: "all .2s ease",
          }}>{o.l}</button>
        ))}
      </div>
    </div>
  );

  return (
    <div style={{
      position: "fixed", bottom: 20, right: 20, zIndex: 100,
      width: 300, padding: 22,
      background: "var(--ink-2)", color: "#fff",
      borderRadius: 14,
      boxShadow: "0 24px 60px rgba(0,0,0,0.28)",
      display: "grid", gap: 18,
      fontFamily: "var(--sans)",
    }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        paddingBottom: 14, borderBottom: "1px solid rgba(255,255,255,0.12)",
      }}>
        <div className="serif" style={{ fontSize: 20, fontFamily: "var(--serif)" }}>Tweaks</div>
        <div style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(255,255,255,0.5)" }}>
          CINFRA
        </div>
      </div>

      <Row label="Hero" value={tweaks.heroTreatment}
        options={[{ v: "photo", l: "Photo + scrim" }, { v: "type", l: "Typographic" }, { v: "mark", l: "Monogram" }]}
        onChange={(v) => update({ heroTreatment: v })} />

      <Row label="Enfoque layout" value={tweaks.focusLayout}
        options={[{ v: "editorial", l: "Editorial list" }, { v: "grid", l: "3-card grid" }]}
        onChange={(v) => update({ focusLayout: v })} />

      <Row label="Texture" value={tweaks.texture}
        options={[{ v: "off", l: "Off" }, { v: "grain", l: "Grain" }, { v: "paper", l: "Paper dots" }]}
        onChange={(v) => update({ texture: v })} />

      <Row label="Section alternation" value={tweaks.alternation}
        options={[{ v: "cream", l: "Cream only" }, { v: "bone", l: "+ Bone" }]}
        onChange={(v) => update({ alternation: v })} />

      <Row label="Sector imagery" value={tweaks.imagery}
        options={[{ v: "on", l: "Photography" }, { v: "off", l: "Typographic" }]}
        onChange={(v) => update({ imagery: v })} />
    </div>
  );
}

/* Simpler fallback hero treatments */
const _Hero = window.Hero;
window.Hero = function WrappedHero({ treatment }) {
  if (treatment === "type") {
    return <HeroTypographic />;
  }
  if (treatment === "mark") {
    return <HeroMark />;
  }
  return <_Hero treatment="photo" />;
};

function HeroTypographic() {
  return (
    <section id="top" style={{
      position: "relative", minHeight: "100vh",
      paddingTop: 140, paddingBottom: 80,
      display: "flex", alignItems: "center",
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "0 40px", width: "100%" }}>
        <div className="reveal eyebrow" style={{ marginBottom: 24 }}>— Consorcio Infraestructura</div>
        <h1 className="serif reveal d1" style={{
          fontSize: "clamp(64px, 11vw, 180px)",
          lineHeight: 0.92, margin: 0, fontWeight: 400,
          letterSpacing: "-0.035em",
        }}>
          Infra<span style={{ fontStyle: "italic" }}>estructura</span>,<br/>
          criterio y<br/>
          permanencia.
        </h1>
        <div className="reveal d3" style={{
          marginTop: 60,
          display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 60,
          paddingTop: 40, borderTop: "1px solid var(--ink-12)",
        }}>
          <p style={{ margin: 0, fontSize: 22, lineHeight: 1.65, color: "var(--ink-75)", maxWidth: 560 }}>
            Una plataforma con visión de largo plazo, orientada a
            oportunidades selectivas en transición energética, infraestructura
            estratégica y nuevas tecnologías.
          </p>
          <div style={{ display: "flex", gap: 12, alignSelf: "end", justifyContent: "flex-end", flexWrap: "wrap" }}>
            <a href="#contacto" className="btn btn-primary">Contacto</a>
            <a href="#enfoque"  className="btn btn-ghost">Conocer más</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function HeroMark() {
  return (
    <section id="top" style={{
      position: "relative", minHeight: "100vh",
      paddingTop: 140, paddingBottom: 80,
      display: "flex", alignItems: "center",
      background: "radial-gradient(60% 80% at 50% 40%, #EFE8D6 0%, var(--cream) 60%)",
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "0 40px", width: "100%", textAlign: "center" }}>
        <div className="reveal" style={{ display: "flex", justifyContent: "center", marginBottom: 48 }}>
          <svg width="180" height="180" viewBox="0 0 200 200" fill="none" aria-hidden>
            <circle cx="100" cy="100" r="98" stroke="var(--ink)" strokeWidth="1" opacity="0.2"/>
            <circle cx="100" cy="100" r="70" stroke="var(--ink)" strokeWidth="1" opacity="0.35"/>
            <path d="M45 105 Q100 40 155 105" stroke="var(--ink)" strokeWidth="1.5" fill="none"/>
            <path d="M45 115 Q100 180 155 115" stroke="var(--ink)" strokeWidth="1.5" fill="none" opacity="0.5"/>
            <text x="100" y="108" textAnchor="middle" className="serif"
                  style={{ fontFamily: "var(--serif)", fontSize: 22, letterSpacing: "0.24em", fill: "var(--ink)" }}>
              CINFRA
            </text>
          </svg>
        </div>
        <div className="eyebrow reveal d1">Consorcio Infraestructura</div>
        <h1 className="serif reveal d2" style={{
          fontSize: "clamp(40px, 6vw, 88px)",
          lineHeight: 1, letterSpacing: "-0.02em",
          margin: "24px auto 0", maxWidth: 1000, fontWeight: 400,
        }}>
          Inversión vanguardista en infraestructura y activos renovables de alta calidad.
        </h1>
        <p className="reveal d3" style={{
          margin: "32px auto 0", maxWidth: 620, fontSize: 18, lineHeight: 1.65, color: "var(--ink-75)",
        }}>
          Una plataforma con visión de largo plazo, orientada a
          oportunidades selectivas en transición energética, infraestructura
          estratégica y nuevas tecnologías.
        </p>
        <div className="reveal d4" style={{ marginTop: 40, display: "flex", justifyContent: "center", gap: 12 }}>
          <a href="#contacto" className="btn btn-primary">Contacto</a>
          <a href="#enfoque"  className="btn btn-ghost">Conocer más</a>
        </div>
      </div>
    </section>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
