/* global React, Icon, Logo, Reveal */
/* ============================================================
   OASIA — Header + Hero + AvatarFrame
   ============================================================ */

const AVATAR_VIDEO = "https://storage.googleapis.com/botgpt-a284d.appspot.com/avatars/6lqAzrTDFUYwoy629m2vNMHiciA2/Revirai2_lite3/idle_video.mp4";

function Header({ onTalkClick }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", on, { passive: true });
    on();
    return () => window.removeEventListener("scroll", on);
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  const navLinks = [
    ["Tu situación", "#situacion"],
    ["Cómo te ayudamos", "#proceso"],
    ["Abogado virtual", "#legal"],
    ["Quiénes somos", "#equipo"],
    ["FAQ", "#faq"],
  ];

  const link = (label, href) => (
    <a href={href} style={{
      fontSize: 14, fontWeight: 500, color: "var(--ink)",
      padding: "8px 4px", letterSpacing: "-0.005em",
      transition: "color .2s",
      whiteSpace: "nowrap",
    }}
      onMouseEnter={(e) => e.currentTarget.style.color = "var(--petrol)"}
      onMouseLeave={(e) => e.currentTarget.style.color = "var(--ink)"}
    >{label}</a>
  );

  return (
    <header style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 40,
      background: scrolled || menuOpen ? "rgba(244, 239, 229, 0.92)" : "transparent",
      backdropFilter: scrolled || menuOpen ? "blur(14px) saturate(140%)" : "none",
      borderBottom: scrolled || menuOpen ? "1px solid var(--line)" : "1px solid transparent",
      transition: "all .35s cubic-bezier(.2,.7,.2,1)",
    }}>
      <div className="container header-bar" style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "18px 32px", gap: 32,
      }}>
        <a href="#top" style={{ display: "inline-flex" }}><Logo size={38} sub={true} /></a>

        <nav className="header-nav" style={{ display: "flex", alignItems: "center", gap: 24, flexShrink: 0 }}>
          {navLinks.map(([l, h]) => <React.Fragment key={h}>{link(l, h)}</React.Fragment>)}
        </nav>

        <div className="header-actions" style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <a href="tel:+34900000000" className="btn btn-sm btn-ghost header-tel" style={{ gap: 6 }}>
            <Icon name="phone" size={14} />
            900 000 000
          </a>
          <button className="btn btn-sm btn-primary header-cta" onClick={onTalkClick}>
            Hablar con Oasia
            <Icon name="arrowRight" size={14} />
          </button>
          <button
            className="header-burger"
            onClick={() => setMenuOpen((v) => !v)}
            aria-label={menuOpen ? "Cerrar menú" : "Abrir menú"}
            style={{
              display: "none",
              width: 40, height: 40,
              background: "transparent",
              border: "1px solid var(--line-strong)",
              borderRadius: "var(--r-pill)",
              cursor: "pointer",
              alignItems: "center", justifyContent: "center",
              color: "var(--ink)",
            }}
          >
            <Icon name={menuOpen ? "x" : "menu"} size={18} />
          </button>
        </div>
      </div>

      {menuOpen && (
        <div className="mobile-menu" style={{
          padding: "8px 24px 24px",
          display: "flex", flexDirection: "column", gap: 4,
          borderTop: "1px solid var(--line)",
        }}>
          {navLinks.map(([l, h]) => (
            <a key={h} href={h} onClick={() => setMenuOpen(false)} style={{
              padding: "14px 4px",
              fontSize: 16, fontWeight: 500,
              color: "var(--ink)",
              borderBottom: "1px solid var(--line)",
            }}>{l}</a>
          ))}
          <a href="tel:+34900000000" style={{
            marginTop: 12,
            padding: "12px 4px",
            fontSize: 15, fontWeight: 600,
            color: "var(--petrol)",
            display: "inline-flex", alignItems: "center", gap: 8,
          }}>
            <Icon name="phone" size={14} />
            900 000 000
          </a>
        </div>
      )}
    </header>
  );
}

/* ============================================================
   Avatar frame — reusable, plays idle video
   ============================================================ */

function AvatarFrame({ size = 360, shadow = true, label = true, status = "Disponible ahora" }) {
  return (
    <div style={{
      position: "relative",
      width: size, height: size,
      borderRadius: "50%",
      overflow: "visible",
    }}>
      {/* soft halo */}
      <div style={{
        position: "absolute", inset: -24,
        background: "radial-gradient(circle at center, rgba(31,79,75,0.25), transparent 65%)",
        filter: "blur(12px)",
        pointerEvents: "none",
      }} />
      {/* breathing ring */}
      <div style={{
        position: "absolute", inset: -8,
        borderRadius: "50%",
        border: "1px solid var(--petrol-line)",
        animation: "softPulse 4s ease-in-out infinite",
      }} />
      <div style={{
        position: "relative",
        width: "100%", height: "100%",
        borderRadius: "50%",
        overflow: "hidden",
        background: "linear-gradient(160deg, #2a6864 0%, #143836 100%)",
        boxShadow: shadow ? "var(--shadow-xl)" : "none",
        border: "4px solid var(--bg-2)",
      }}>
        <video
          src={AVATAR_VIDEO}
          autoPlay
          loop
          muted
          playsInline
          style={{
            width: "100%", height: "100%",
            objectFit: "cover",
            objectPosition: "center 18%",
            display: "block",
          }}
        />
      </div>

      {label && (
        <div style={{
          position: "absolute",
          bottom: 14,
          left: "50%",
          transform: "translateX(-50%)",
          background: "rgba(20, 56, 54, 0.78)",
          backdropFilter: "blur(8px)",
          border: "1px solid rgba(248, 244, 234, 0.22)",
          padding: "7px 14px",
          borderRadius: "var(--r-pill)",
          fontSize: 12.5,
          fontWeight: 600,
          color: "#fff",
          display: "inline-flex", alignItems: "center", gap: 8,
          whiteSpace: "nowrap",
          zIndex: 2,
        }}>
          <span style={{
            display: "inline-block", width: 7, height: 7, borderRadius: "50%",
            background: "#7ad19c",
            boxShadow: "0 0 0 3px rgba(122, 209, 156, 0.25)",
          }} />
          {status}
        </div>
      )}
    </div>
  );
}

/* ============================================================
   Hero
   ============================================================ */

function Hero({ onTalkClick }) {
  return (
    <section id="top" className="hero-section" style={{
      position: "relative",
      paddingTop: 140, paddingBottom: 80,
      overflow: "hidden",
    }}>
      {/* Background — abstract paper texture + soft glow */}
      <div style={{
        position: "absolute", inset: 0, zIndex: 0, pointerEvents: "none",
        background: `
          radial-gradient(60% 60% at 85% 30%, rgba(31, 79, 75, 0.10) 0%, transparent 60%),
          radial-gradient(50% 60% at 10% 80%, rgba(183, 101, 74, 0.06) 0%, transparent 65%)
        `,
      }} />
      <div className="grain" />

      <div className="container hero-grid" style={{
        position: "relative", zIndex: 2,
        display: "grid",
        gridTemplateColumns: "1.15fr 1fr",
        gap: 64,
        alignItems: "center",
        minHeight: "calc(100vh - 220px)",
      }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
          <Reveal>
            <div className="chip" style={{ gap: 8 }}>
              <Icon name="leaf" size={14} />
              Acompañamiento al deudor hipotecario
            </div>
          </Reveal>

          <Reveal delay={80}>
            <h1 style={{
              fontSize: "clamp(48px, 5.8vw, 80px)",
              fontWeight: 500,
              lineHeight: 1.02,
              letterSpacing: "-0.028em",
            }}>
              Si tu hipoteca <br/>
              te <em style={{
                fontStyle: "italic",
                color: "var(--petrol)",
                fontWeight: 500,
              }}>asfixia</em>, hay <br/>
              una salida.
            </h1>
          </Reveal>

          <Reveal delay={180}>
            <p className="lead" style={{ maxWidth: 540 }}>
              Oasia acompaña a personas con préstamos hipotecarios en dificultad —
              impago temprano, ejecución abierta, dación o refinanciación — y les
              ayuda a construir, sin presión, una salida ordenada con un inversor
              profesional al otro lado.
            </p>
          </Reveal>

          <Reveal delay={260}>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 8 }}>
              <button className="btn btn-primary btn-lg" onClick={onTalkClick}>
                Empezar una conversación
                <Icon name="arrowRight" size={16} />
              </button>
              <a href="#situacion" className="btn btn-ghost btn-lg">
                Ver mi situación
              </a>
            </div>
          </Reveal>

          <Reveal delay={340}>
            <div style={{
              display: "flex", gap: 28, alignItems: "center",
              paddingTop: 28, marginTop: 8,
              borderTop: "1px solid var(--line)",
              flexWrap: "wrap",
            }}>
              {[
                ["lock", "Confidencial"],
                ["euro", "Sin coste inicial"],
                ["clock", "Sin compromiso"],
                ["scale", "Información jurídica clara"],
              ].map(([icn, label]) => (
                <div key={label} style={{
                  display: "inline-flex", alignItems: "center", gap: 8,
                  fontSize: 13, color: "var(--ink-2)", fontWeight: 500,
                }}>
                  <Icon name={icn} size={16} color="var(--petrol)" />
                  {label}
                </div>
              ))}
            </div>
          </Reveal>
        </div>

        {/* Right: Avatar + AI-availability card */}
        <Reveal delay={120}>
          <div style={{
            display: "flex", flexDirection: "column", alignItems: "center",
            position: "relative",
          }}>
            <AvatarFrame size={340} status="Lucía · Disponible ahora" />

            <div className="card" style={{
              marginTop: 40,
              maxWidth: 380,
              textAlign: "left",
              boxShadow: "var(--shadow-lg)",
              padding: 22,
            }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
                <div style={{
                  width: 40, height: 40, flexShrink: 0,
                  background: "var(--petrol-soft)",
                  borderRadius: "50%",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <Icon name="msg" size={20} color="var(--petrol)" />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>
                    Habla con Lucía cuando quieras
                  </div>
                  <p style={{ fontSize: 13.5, lineHeight: 1.5, color: "var(--ink-2)" }}>
                    Nuestra asistente escucha 24/7 por web, WhatsApp o teléfono.
                    Sin juicios, sin presión.
                  </p>
                </div>
              </div>

              <div style={{
                display: "flex", gap: 8, marginTop: 16, paddingTop: 16,
                borderTop: "1px solid var(--line)",
              }}>
                {[
                  ["globe", "Web"],
                  ["whatsapp", "WhatsApp"],
                  ["phone", "Teléfono"],
                ].map(([icn, label]) => (
                  <div key={label} style={{
                    flex: 1,
                    padding: "10px 8px",
                    border: "1px solid var(--line)",
                    borderRadius: "var(--r-md)",
                    fontSize: 12, fontWeight: 600,
                    color: "var(--ink-2)",
                    display: "flex", flexDirection: "column",
                    alignItems: "center", gap: 6,
                    background: "var(--bg-2)",
                  }}>
                    <Icon name={icn} size={16} color="var(--petrol)" />
                    {label}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </Reveal>
      </div>

      {/* Scroll indicator */}
      <div style={{
        position: "absolute", left: "50%", bottom: 24,
        transform: "translateX(-50%)",
        display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
        color: "var(--ink-3)",
        fontFamily: "var(--font-mono)",
        fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
      }}>
        <span>Cómo te ayudamos</span>
        <Icon name="arrowDown" size={14} />
      </div>
    </section>
  );
}

Object.assign(window, { Header, Hero, AvatarFrame, AVATAR_VIDEO });
