/* global React, Wordmark, Icon, WA_URL, PHONE_FMT, EMAIL, Reveal */
const { useState: useStateHome, useEffect: useEffectHome } = React;

const INDUSTRIAL_URL = 'empresas.html';
const HOGAR_URL = 'SLF Solar - Hogar.html';

/* ===========================================================
   Shared minimal header for the welcome / Inicio page
   =========================================================== */
function InicioNav({ tone = 'dark' }) {
  return (
    <header style={{
      position: 'absolute', top: 0, left: 0, right: 0, zIndex: 20,
      padding: '20px 0',
    }}>
      <div className="container flex items-center justify-between">
        <a href="#top" aria-label="Inicio SLF Solar">
          <Wordmark variant="full" tone={tone} size={20} />
        </a>
        <div className="flex items-center gap-3">
          <a className="btn btn-wa btn-sm" href={WA_URL} target="_blank" rel="noopener">
            <Icon.Whatsapp size={16} /> WhatsApp
          </a>
        </div>
      </div>
    </header>
  );
}

/* ===========================================================
   World panel content (shared between layouts)
   =========================================================== */
const HOGAR = {
  href: HOGAR_URL,
  eyebrow: 'Hogar & Familia',
  title: 'Tu casa, con energía propia',
  desc: 'Baja tu cuenta de luz con energía solar, agua caliente y climatización. Energía renovable, asesoría cercana y respaldo de verdad.',
  bullets: ['Ahorro mensual concreto', 'Energía 100% renovable', 'Asesoría por WhatsApp'],
  cta: 'Soluciones para mi hogar',
  photo: 'uploads/sunlightfree_energia_limpia.webp',
  phTag: 'FOTO · familia frente a su casa con paneles solares',
};
const INDUSTRIAL = {
  href: INDUSTRIAL_URL,
  eyebrow: 'Empresas & Industria',
  title: 'Energía que no se detiene',
  desc: 'Plantas solares industriales, respaldo con baterías, termosolar, cargadores EV y torres de iluminación híbridas. Ingeniería, instalación y O&M.',
  bullets: ['Fichas técnicas reales', 'Casos verificables', 'Operación y mantenimiento'],
  cta: 'Soluciones industriales',
  photo: 'uploads/empresas-hero-fabrica-techo-solar-cdd65be9.webp',
  phTag: 'FOTO · planta solar industrial — vista aérea',
};

/* ===========================================================
   LAYOUT A — Split screen (two worlds, 50/50)
   =========================================================== */
function SplitHome() {
  const [hover, setHover] = useStateHome(null); // 'hogar' | 'ind' | null

  const flex = (key) => {
    if (hover === null) return 1;
    return hover === key ? 1.25 : 0.75;
  };

  return (
    <section id="top" style={{ position: 'relative', minHeight: '100vh', background: '#0B2545' }}>
      <InicioNav tone="light" />

      <div className="split-wrap" style={{ display: 'flex', minHeight: '100vh', width: '100%' }}>
        {/* HOGAR side */}
        <a
          href={HOGAR.href}
          onMouseEnter={() => setHover('hogar')}
          onMouseLeave={() => setHover(null)}
          className="split-side"
          style={{
            flex: flex('hogar'),
            position: 'relative', overflow: 'hidden',
            transition: 'flex .5s cubic-bezier(.4,0,.2,1)',
            display: 'flex', alignItems: 'flex-end',
            background: 'linear-gradient(180deg, #FBF8F1 0%, #F4EEE1 100%)',
            color: 'var(--warm-ink)',
            textAlign: 'left',
          }}
        >
          {/* warm photo */}
          <div className="ph-img" aria-hidden="true" style={{
            position: 'absolute', inset: 0, borderRadius: 0,
            backgroundImage: `url("${HOGAR.photo}")`, backgroundSize: 'cover', backgroundPosition: 'center',
          }}>
          </div>
          {/* readability scrim */}
          <div aria-hidden="true" style={{ position: 'absolute', inset: 0, background: 'linear-gradient(0deg, rgba(251,248,241,.96) 8%, rgba(251,248,241,.55) 45%, rgba(251,248,241,0) 80%)' }} />
          <WorldContent data={HOGAR} accent="var(--leaf)" accentInk="#fff" muted="var(--warm-slate)" />
        </a>

        {/* INDUSTRIAL side */}
        <a
          href={INDUSTRIAL.href}
          onMouseEnter={() => setHover('ind')}
          onMouseLeave={() => setHover(null)}
          className="split-side"
          style={{
            flex: flex('ind'),
            position: 'relative', overflow: 'hidden',
            transition: 'flex .5s cubic-bezier(.4,0,.2,1)',
            display: 'flex', alignItems: 'flex-end',
            background: 'linear-gradient(180deg, #133362 0%, #061328 100%)',
            color: '#fff', textAlign: 'left',
          }}
        >
          <div aria-hidden="true" style={{ position: 'absolute', inset: 0, backgroundImage: `url("${INDUSTRIAL.photo}")`, backgroundSize: 'cover', backgroundPosition: 'center' }} />
          <div aria-hidden="true" style={{ position: 'absolute', inset: 0, background: 'linear-gradient(0deg, rgba(6,19,40,.96) 8%, rgba(6,19,40,.5) 45%, rgba(6,19,40,.1) 80%)' }} />
          <WorldContent data={INDUSTRIAL} accent="var(--solar)" accentInk="#0B2545" muted="rgba(255,255,255,.7)" onDark />
        </a>
      </div>

      {/* Center brand medallion */}
      <div className="split-center" style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        zIndex: 10, textAlign: 'center', pointerEvents: 'none',
      }}>
        <div style={{
          background: '#fff', borderRadius: 999, padding: '14px 22px',
          boxShadow: '0 18px 48px -12px rgba(11,37,69,.4)', display: 'inline-flex',
          flexDirection: 'column', alignItems: 'center', gap: 4,
        }}>
          <Wordmark variant="compact" tone="dark" size={22} />
          <span className="mono" style={{ fontSize: 10, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--leaf-700)' }}>Tu Energía, Nuestra Pasión</span>
        </div>
      </div>

      <style>{`
        @media (max-width: 860px) {
          .split-wrap { flex-direction: column !important; }
          .split-side { flex: none !important; min-height: 70vh; }
          .split-center { display: none !important; }
        }
      `}</style>
    </section>
  );
}

function WorldContent({ data, accent, accentInk, muted, onDark }) {
  return (
    <div className="container" style={{ position: 'relative', zIndex: 4, padding: '0 24px 64px' }}>
      <div style={{ maxWidth: 460 }}>
        <span className="eyebrow" style={{ color: accent }}>{data.eyebrow}</span>
        <h2 className="h-1" style={{ marginTop: 12, color: onDark ? '#fff' : 'var(--warm-ink)' }}>{data.title}</h2>
        <p className="mt-4" style={{ color: muted, fontSize: 17, lineHeight: 1.55, textWrap: 'pretty' }}>{data.desc}</p>
        <ul className="clean mt-4" style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {data.bullets.map((b) => (
            <li key={b} className="flex items-center gap-2" style={{ fontSize: 14, color: muted, padding: 0 }}>
              <span style={{ width: 18, height: 18, borderRadius: '50%', background: accent, color: accentInk, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20,6 9,17 4,12"/></svg>
              </span>
              {b}
            </li>
          ))}
        </ul>
        <span className="btn btn-lg mt-8" style={{ background: accent, color: accentInk, borderColor: accent, pointerEvents: 'none' }}>
          {data.cta} <Icon.ArrowSmall />
        </span>
      </div>
    </div>
  );
}

/* ===========================================================
   LAYOUT B — Editorial (centered promise + two entry cards)
   =========================================================== */
function EditorialHome() {
  return (
    <>
      <section id="top" style={{ position: 'relative', overflow: 'hidden', background: 'linear-gradient(180deg, #FBF8F1 0%, #FFFFFF 60%)' }}>
        <InicioNav tone="dark" />
        <div className="container" style={{ position: 'relative', zIndex: 2, padding: '160px 24px 56px', textAlign: 'center' }}>
          <Reveal>
            <span className="badge badge-green" style={{ background: 'var(--leaf-50)', color: 'var(--leaf-700)', borderColor: 'rgba(47,158,68,.25)' }}>
              <span className="pulse-dot" style={{ background: 'var(--leaf)' }} /> SLF Solar · operando en Chile desde 2014
            </span>
          </Reveal>
          <Reveal delay={60}>
            <h1 className="h-display" style={{ marginTop: 24, maxWidth: 900, marginLeft: 'auto', marginRight: 'auto' }}>
              Tu Energía, <span style={{ color: 'var(--leaf)' }}>Nuestra Pasión.</span>
            </h1>
          </Reveal>
          <Reveal delay={120}>
            <p className="lead" style={{ marginTop: 20, maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
              Energía solar para tu hogar y para tu industria. Elige tu camino y te acompañamos desde el primer cálculo hasta la operación.
            </p>
          </Reveal>
        </div>

        {/* Two entry cards */}
        <div className="container" style={{ paddingBottom: 96, position: 'relative', zIndex: 2 }}>
          <div className="grid grid-2" style={{ gap: 24, alignItems: 'stretch' }}>
            <Reveal delay={160}><EntryCard data={HOGAR} variant="warm" /></Reveal>
            <Reveal delay={220}><EntryCard data={INDUSTRIAL} variant="industrial" /></Reveal>
          </div>
        </div>
      </section>

      <PromiseStrip />
      <InicioFooter />
    </>
  );
}

function EntryCard({ data, variant }) {
  const warm = variant === 'warm';
  const accent = warm ? 'var(--leaf)' : 'var(--solar)';
  const accentInk = warm ? '#fff' : '#0B2545';
  return (
    <a href={data.href} className="card card-hover entry-card" style={{
      display: 'flex', flexDirection: 'column', overflow: 'hidden', textAlign: 'left', height: '100%',
      borderColor: warm ? 'var(--warm-line)' : 'var(--line)',
      background: warm ? 'var(--cream)' : '#fff',
    }}>
      {/* media */}
      <div className="ph-img" aria-hidden="true" style={{
        aspectRatio: '3 / 2', borderRadius: 0, position: 'relative',
        backgroundImage: `url("${data.photo}")`, backgroundSize: 'cover', backgroundPosition: 'center',
      }}>
      </div>
      {/* body */}
      <div style={{ padding: '28px 28px 32px', display: 'flex', flexDirection: 'column', flex: 1 }}>
        <span className="eyebrow" style={{ color: accent }}>{data.eyebrow}</span>
        <h2 className="h-2" style={{ marginTop: 10 }}>{data.title}</h2>
        <p className="body mt-3" style={{ fontSize: 16, lineHeight: 1.55 }}>{data.desc}</p>
        <ul className="clean mt-4" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {data.bullets.map((b) => (
            <li key={b} className="flex items-center gap-2" style={{ fontSize: 13, color: 'var(--slate)', padding: 0 }}>
              <span style={{ color: accent, display: 'inline-flex' }}><Icon.Check /></span>{b}
            </li>
          ))}
        </ul>
        <div style={{ flex: 1 }} />
        <span className="btn btn-lg mt-8" style={{ alignSelf: 'flex-start', background: accent, color: accentInk, borderColor: accent }}>
          {data.cta} <Icon.ArrowSmall />
        </span>
      </div>
    </a>
  );
}

/* ===========================================================
   Shared brand-promise strip + footer (used by Editorial)
   =========================================================== */
function PromiseStrip() {
  const items = [
    { n: '12', s: ' años', l: 'operando en Chile' },
    { n: '+2.500', s: '', l: 'instalaciones realizadas' },
    { n: 'Arica', s: '→ Pta. Montt', l: 'cobertura nacional' },
    { n: '100%', s: '', l: 'energía renovable' },
  ];
  return (
    <section className="bg-blue-deep" style={{ padding: '56px 0' }}>
      <div className="container">
        <div className="grid grid-4" style={{ gap: 16 }}>
          {items.map((it) => (
            <div key={it.l} style={{ textAlign: 'center' }}>
              <div className="stat-num on-blue" style={{ fontSize: 'clamp(26px,3vw,38px)' }}>{it.n}<span style={{ fontSize: '.5em', color: 'rgba(255,255,255,.6)' }}>{it.s}</span></div>
              <div className="stat-label on-blue">{it.l}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function InicioFooter() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr 1fr', gap: 40 }}>
          <div>
            <Wordmark variant="full" tone="light" size={22} />
            <p className="mt-4" style={{ maxWidth: 320, color: 'rgba(255,255,255,.6)', fontSize: 14 }}>
              Energía solar para hogares e industria en Chile. Tu Energía, Nuestra Pasión.
            </p>
            <a className="btn btn-wa btn-sm mt-6" href={WA_URL} target="_blank" rel="noopener" style={{ alignSelf: 'flex-start' }}>
              <Icon.Whatsapp size={16} /> Escríbenos por WhatsApp
            </a>
          </div>
          <div>
            <h4>Explorar</h4>
            <ul className="clean" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <li><a href={HOGAR_URL}>Hogar & Familia</a></li>
              <li><a href={INDUSTRIAL_URL}>Empresas & Industria</a></li>
              <li><a href="SLF Energia - Nosotros.html">Nosotros</a></li>
              <li><a href="SLF Energia - Contacto.html">Contacto</a></li>
            </ul>
          </div>
          <div>
            <h4>Contacto</h4>
            <ul className="clean" style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14 }}>
              <li className="flex items-center gap-2"><Icon.Phone /> {PHONE_FMT}</li>
              <li className="flex items-center gap-2"><Icon.Mail /> {EMAIL}</li>
              <li className="flex items-center gap-2"><Icon.Clock /> Lun a Vie · 9–18 h</li>
            </ul>
          </div>
        </div>
        <hr className="hr hr-onblue mt-12 mb-6" />
        <div className="flex items-center justify-between flex-wrap gap-3" style={{ fontSize: 12, color: 'rgba(255,255,255,.45)' }}>
          <span className="mono">© 2026 SLF Solar · Sunlightfree</span>
          <span className="mono">Tu Energía, Nuestra Pasión</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { SplitHome, EditorialHome, InicioNav, INDUSTRIAL_URL, HOGAR_URL });
