// x21 Studio — main React components
// Depends on: window.X21_CONTENT, window.X21_BRANDS

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

// ------------------- Logo mark (animated gradient stripe) -------------------
function AccentLine({ className = "" }) {
  return <span className={`accent-line ${className}`} />;
}

// ------------------- Navigation -------------------
function Nav({ lang, setLang, t }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { id: "services", label: t.nav.services },
    { id: "packages", label: t.nav.packages },
    { id: "transformations", label: t.nav.transformations },
    { id: "about", label: t.nav.about },
    { id: "faq", label: t.nav.faq },
    { id: "contact", label: t.nav.contact },
  ];

  const jump = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    setMobileOpen(false);
  };

  return (
    <header className={`nav ${scrolled ? "nav--scrolled" : ""}`}>
      <div className="nav__inner">
        <a href="#top" className="nav__logo" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: "smooth" }); }}>
          <img src="assets/x21-logo.jpeg" alt="x21 Studio" />
        </a>
        <nav className="nav__links">
          {links.map((l) => (
            <button key={l.id} onClick={() => jump(l.id)} className="nav__link">
              {l.label}
            </button>
          ))}
        </nav>
        <div className="nav__right">
          <div className="lang-toggle" role="group" aria-label="Language">
            <button
              className={lang === "de" ? "is-active" : ""}
              onClick={() => setLang("de")}
              aria-pressed={lang === "de"}
            >DE</button>
            <span className="lang-toggle__sep">|</span>
            <button
              className={lang === "en" ? "is-active" : ""}
              onClick={() => setLang("en")}
              aria-pressed={lang === "en"}
            >EN</button>
          </div>
          <button className="btn btn--gradient btn--sm nav__cta" onClick={() => jump("contact")}>
            {t.nav.cta}
          </button>
          <button
            className={`nav__burger ${mobileOpen ? "is-open" : ""}`}
            onClick={() => setMobileOpen(!mobileOpen)}
            aria-label="Menu"
          >
            <span /><span /><span />
          </button>
        </div>
      </div>
      {mobileOpen && (
        <div className="nav__mobile">
          {links.map((l) => (
            <button key={l.id} onClick={() => jump(l.id)}>{l.label}</button>
          ))}
          <button className="btn btn--gradient" onClick={() => jump("contact")}>{t.nav.cta}</button>
        </div>
      )}
    </header>
  );
}

// ------------------- Hero visual: animated gradient orb + brand grid  -------------------
function HeroVisual() {
  return (
    <div className="hero-visual">
      <div className="hero-orb hero-orb--a" />
      <div className="hero-orb hero-orb--b" />
      <div className="hero-orb hero-orb--c" />

      {/* A floating "brand preview" card showing the output concept */}
      <div className="hero-card hero-card--back">
        <div className="hero-card__header">
          <span className="hero-card__dot" /><span className="hero-card__dot" /><span className="hero-card__dot" />
          <span className="hero-card__label">brand.pdf</span>
        </div>
        <div className="hero-card__body">
          <div className="hero-card__row">
            <div className="hero-card__swatch" style={{ background: "#1A1F2E" }} />
            <div className="hero-card__swatch" style={{ background: "#3B8FD4" }} />
            <div className="hero-card__swatch" style={{ background: "#8B5CF6" }} />
            <div className="hero-card__swatch" style={{ background: "#EEF0F3", border: "1px solid rgba(0,0,0,0.08)" }} />
          </div>
          <div className="hero-card__type">
            <div className="hero-card__type-big">Aa</div>
            <div className="hero-card__type-meta">
              <div>Inter Tight</div>
              <div className="hero-card__muted">Display · 64 / 72</div>
            </div>
          </div>
          <div className="hero-card__lines">
            <span style={{ width: "90%" }} />
            <span style={{ width: "70%" }} />
            <span style={{ width: "50%" }} />
          </div>
        </div>
      </div>

      <div className="hero-card hero-card--front">
        <div className="hero-card__mark">
          <svg viewBox="0 0 80 80" width="56" height="56">
            <defs>
              <linearGradient id="heroMarkGrad" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0" stopColor="#3B8FD4"/>
                <stop offset="1" stopColor="#8B5CF6"/>
              </linearGradient>
            </defs>
            <path d="M 15 15 L 40 40 L 15 65 M 65 15 L 40 40 L 65 65" fill="none" stroke="url(#heroMarkGrad)" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div className="hero-card__brand">
          <div className="hero-card__brand-name">STUDIO NORDEN</div>
          <div className="hero-card__brand-sub">est. 2026 · brand identity</div>
        </div>
      </div>

      <div className="hero-grid-dots" />
    </div>
  );
}

// ------------------- Hero -------------------
function Hero({ t, jump }) {
  return (
    <section id="top" className="hero">
      <div className="container hero__inner">
        <div className="hero__text">
          <div className="eyebrow">
            <span className="eyebrow__dot" />
            {t.hero.eyebrow}
          </div>
          <h1 className="hero__h1">
            <span className="hero__h1-line">{t.hero.h1a}</span>
            <span className="hero__h1-line hero__h1-line--grad">{t.hero.h1b}</span>
          </h1>
          <div className="hero__sub">
            <span className="hero__sub-quote">“{t.hero.sub}”</span>
          </div>
          <p className="hero__body">{t.hero.body}</p>
          <div className="hero__ctas">
            <button className="btn btn--gradient" onClick={() => jump("packages")}>
              {t.hero.primary}
              <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <button className="btn btn--ghost" onClick={() => jump("transformations")}>
              {t.hero.secondary}
            </button>
          </div>
          <div className="hero__badges">
            <div className="hero-badge"><span className="hero-badge__dot" />{t.hero.badge1}</div>
            <div className="hero-badge"><span className="hero-badge__dot" />{t.hero.badge2}</div>
            <div className="hero-badge"><span className="hero-badge__dot" />{t.hero.badge3}</div>
          </div>
        </div>
        <HeroVisual />
      </div>
    </section>
  );
}

// ------------------- What we do -------------------
function WhatWeDo({ t }) {
  const cards = [
    {
      n: "01",
      title: t.what.c1t,
      desc: t.what.c1d,
      icon: (
        <svg viewBox="0 0 40 40" width="28" height="28" fill="none">
          <circle cx="20" cy="20" r="14" stroke="currentColor" strokeWidth="1.6"/>
          <path d="M 13 13 L 27 27 M 27 13 L 13 27" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
        </svg>
      ),
    },
    {
      n: "02",
      title: t.what.c2t,
      desc: t.what.c2d,
      icon: (
        <svg viewBox="0 0 40 40" width="28" height="28" fill="none">
          <rect x="8" y="8" width="24" height="24" rx="4" stroke="currentColor" strokeWidth="1.6"/>
          <circle cx="15" cy="17" r="1.6" fill="currentColor"/>
          <circle cx="25" cy="17" r="1.6" fill="currentColor"/>
          <path d="M 14 25 Q 20 29 26 25" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" fill="none"/>
          <path d="M 20 4 L 20 8 M 4 20 L 8 20 M 32 20 L 36 20 M 20 32 L 20 36" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
        </svg>
      ),
    },
    {
      n: "03",
      title: t.what.c3t,
      desc: t.what.c3d,
      icon: (
        <svg viewBox="0 0 40 40" width="28" height="28" fill="none">
          <path d="M 22 6 L 10 24 L 20 24 L 18 34 L 30 16 L 20 16 Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
        </svg>
      ),
    },
  ];

  return (
    <section id="services" className="section section--light">
      <div className="container">
        <SectionHead eyebrow={t.what.eyebrow} title={t.what.h} sub={t.what.sub} />
        <div className="feature-grid">
          {cards.map((c, i) => (
            <div key={i} className="feature" style={{ animationDelay: `${i * 80}ms` }}>
              <div className="feature__icon">{c.icon}</div>
              <div className="feature__num">{c.n}</div>
              <h3 className="feature__title">{c.title}</h3>
              <p className="feature__desc">{c.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ------------------- Packages -------------------
function Packages({ t, jump, highlightPackage = "standard" }) {
  const pkgs = ["starter","standard","premium"].map((key) => ({
    key,
    data: t.pkg[key],
    highlight: key === highlightPackage,
    cta: key === highlightPackage ? "gradient" : "ghost",
  }));

  return (
    <section id="packages" className="section">
      <div className="container">
        <SectionHead eyebrow={t.pkg.eyebrow} title={t.pkg.h} sub={t.pkg.sub} />
        <div className="pkg-grid">
          {pkgs.map((p) => (
            <div key={p.key} className={`pkg ${p.highlight ? "pkg--highlight" : ""}`}>
              {p.highlight && <div className="pkg__badge">{t.pkg.popular}</div>}
              <div className="pkg__head">
                <div className="pkg__name">{p.data.name}</div>
                <div className="pkg__price">
                  <span className="pkg__price-num">{p.data.price}</span>
                  <span className="pkg__price-sub">{p.data.priceSub}</span>
                </div>
                <div className="pkg__desc">{p.data.desc}</div>
              </div>
              <ul className="pkg__items">
                {p.data.items.map((item, i) => (
                  <li key={i}>
                    <svg viewBox="0 0 16 16" width="14" height="14" className="pkg__check">
                      <path d="M 3 8 L 7 12 L 13 4" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
              {p.data.canDo && (
                <div className="pkg__extra">
                  <div className="pkg__extra-col">
                    <div className="pkg__extra-title">{p.data.canDoTitle}</div>
                    <ul className="pkg__extra-list">
                      {p.data.canDo.map((it, i) => (
                        <li key={i}>{it}</li>
                      ))}
                    </ul>
                  </div>
                  <div className="pkg__extra-col">
                    <div className="pkg__extra-title">{p.data.nextTitle}</div>
                    <ul className="pkg__extra-list pkg__extra-list--next">
                      {p.data.next.map((it, i) => (
                        <li key={i}>{it}</li>
                      ))}
                    </ul>
                    {p.data.nextLink && (
                      <a
                        className="pkg__extra-link"
                        href="#packages"
                        onClick={(e) => { e.preventDefault(); jump("packages"); }}
                      >{p.data.nextLink}</a>
                    )}
                  </div>
                </div>
              )}
              <button
                className={`btn ${p.cta === "gradient" ? "btn--gradient" : "btn--outline"} pkg__cta`}
                onClick={() => jump("contact")}
              >
                {p.data.cta}
              </button>
            </div>
          ))}
        </div>
        <p className="pkg__note">{t.pkg.note}</p>
      </div>
    </section>
  );
}

// ------------------- Before/After slider -------------------
function BeforeAfter({ before, after, beforeLabel, afterLabel, dragLabel }) {
  const [pos, setPos] = useState(50);
  const ref = useRef(null);
  const dragging = useRef(false);

  const move = useCallback((clientX) => {
    const r = ref.current?.getBoundingClientRect();
    if (!r) return;
    let p = ((clientX - r.left) / r.width) * 100;
    p = Math.max(0, Math.min(100, p));
    setPos(p);
  }, []);

  useEffect(() => {
    const onMove = (e) => {
      if (!dragging.current) return;
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      move(x);
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    window.addEventListener("touchmove", onMove, { passive: false });
    window.addEventListener("touchend", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
      window.removeEventListener("touchmove", onMove);
      window.removeEventListener("touchend", onUp);
    };
  }, [move]);

  const start = (e) => {
    dragging.current = true;
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    move(x);
  };

  return (
    <div className="ba" ref={ref} onMouseDown={start} onTouchStart={start}>
      <div className="ba__before" dangerouslySetInnerHTML={{ __html: before }} />
      <div className="ba__after" style={{ clipPath: `inset(0 0 0 ${pos}%)` }} dangerouslySetInnerHTML={{ __html: after }} />
      <div className="ba__label ba__label--before">{beforeLabel}</div>
      <div className="ba__label ba__label--after">{afterLabel}</div>
      <div className="ba__divider" style={{ left: `${pos}%` }}>
        <div className="ba__handle" aria-label={dragLabel}>
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path d="M 9 6 L 4 12 L 9 18 M 15 6 L 20 12 L 15 18" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

// ------------------- Transformations -------------------
function Transformations({ t }) {
  const items = t.trans.items;
  const brands = window.X21_BRANDS;

  return (
    <section id="transformations" className="section section--light">
      <div className="container">
        <SectionHead eyebrow={t.trans.eyebrow} title={t.trans.h} sub={t.trans.sub} />
        <div className="trans__disclaimer">
          <svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><circle cx="10" cy="10" r="8" fill="none" stroke="currentColor" strokeWidth="1.4"/><path d="M 10 6 L 10 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/><circle cx="10" cy="14" r="0.9" fill="currentColor"/></svg>
          <span>{t.trans.disclaimer}</span>
        </div>
        <div className="trans-stack">
          {items.map((it, i) => (
            <div key={i} className="trans">
              <div className="trans__meta">
                <div className="trans__num">0{i + 1}</div>
                <div className="trans__name">{it.name}</div>
                <div className="trans__sector">{it.sector}</div>
                <div className="trans__caption">“{it.caption}”</div>
                <div className="trans__hint">
                  <svg viewBox="0 0 24 24" width="14" height="14"><path d="M 9 6 L 4 12 L 9 18 M 15 6 L 20 12 L 15 18" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  {t.trans.drag}
                </div>
              </div>
              <BeforeAfter
                before={brands[i].before}
                after={brands[i].after}
                beforeLabel={t.trans.beforeLabel}
                afterLabel={t.trans.afterLabel}
                dragLabel={t.trans.drag}
              />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ------------------- About -------------------
function About({ t }) {
  return (
    <section id="about" className="section">
      <div className="container about">
        <div className="about__left">
          <SectionHead eyebrow={t.about.eyebrow} title={t.about.h} align="left" />
          <p className="about__p">{t.about.p1}</p>
          <p className="about__p">{t.about.p2}</p>
          <p className="about__p">{t.about.p3}</p>
        </div>
        <div className="about__right">
          <AboutGrid />
        </div>
      </div>
    </section>
  );
}

function AboutGrid() {
  // Abstract brand system visual
  return (
    <div className="brand-grid">
      <div className="brand-grid__cell brand-grid__cell--logo">
        <svg viewBox="0 0 100 100" width="100%" height="100%">
          <defs>
            <linearGradient id="agGrad" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0" stopColor="#3B8FD4"/>
              <stop offset="1" stopColor="#8B5CF6"/>
            </linearGradient>
          </defs>
          <path d="M 25 25 L 50 50 L 25 75 M 75 25 L 50 50 L 75 75" fill="none" stroke="url(#agGrad)" strokeWidth="5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        <div className="brand-grid__tag">Mark</div>
      </div>
      <div className="brand-grid__cell brand-grid__cell--type">
        <div className="brand-grid__aa">Aa</div>
        <div className="brand-grid__tag">Type</div>
      </div>
      <div className="brand-grid__cell brand-grid__cell--pal">
        <div className="brand-grid__swatches">
          <span style={{ background: "#1A1F2E" }} />
          <span style={{ background: "#3B8FD4" }} />
          <span style={{ background: "#8B5CF6" }} />
          <span style={{ background: "#EEF0F3" }} />
        </div>
        <div className="brand-grid__tag">Palette</div>
      </div>
      <div className="brand-grid__cell brand-grid__cell--grid">
        <svg viewBox="0 0 100 100" width="100%" height="100%">
          {[...Array(10)].map((_, i) => (
            <line key={`v${i}`} x1={i * 10} y1="0" x2={i * 10} y2="100" stroke="#1A1F2E" strokeWidth="0.3" opacity="0.25"/>
          ))}
          {[...Array(10)].map((_, i) => (
            <line key={`h${i}`} x1="0" y1={i * 10} x2="100" y2={i * 10} stroke="#1A1F2E" strokeWidth="0.3" opacity="0.25"/>
          ))}
          <circle cx="50" cy="50" r="20" fill="none" stroke="#3B8FD4" strokeWidth="1"/>
          <circle cx="50" cy="50" r="34" fill="none" stroke="#8B5CF6" strokeWidth="1"/>
        </svg>
        <div className="brand-grid__tag">System</div>
      </div>
    </div>
  );
}

// ------------------- FAQ -------------------
function FAQ({ t }) {
  const [open, setOpen] = useState(0);
  return (
    <section id="faq" className="section section--light">
      <div className="container faq">
        <SectionHead eyebrow={t.faq.eyebrow} title={t.faq.h} align="left" />
        <div className="faq__list">
          {t.faq.items.map((item, i) => {
            const isOpen = open === i;
            return (
              <div key={i} className={`faq__item ${isOpen ? "is-open" : ""}`}>
                <button className="faq__q" onClick={() => setOpen(isOpen ? -1 : i)} aria-expanded={isOpen}>
                  <span className="faq__q-num">0{i + 1}</span>
                  <span className="faq__q-text">{item.q}</span>
                  <span className="faq__q-icon">
                    <svg viewBox="0 0 20 20" width="16" height="16"><path d="M 4 8 L 10 14 L 16 8" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </span>
                </button>
                <div className="faq__a-wrap">
                  <div className="faq__a">{item.a}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ------------------- Contact -------------------
function Contact({ t }) {
  const [form, setForm] = useState({ name: "", email: "", company: "", message: "", gdpr: false });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = true;
    if (!form.email.trim() || !/@/.test(form.email)) er.email = true;
    if (!form.message.trim()) er.message = true;
    if (!form.gdpr) er.gdpr = true;
    setErrors(er);
    if (Object.keys(er).length === 0) {
      setSent(true);
      setTimeout(() => {
        setSent(false);
        setForm({ name: "", email: "", company: "", message: "", gdpr: false });
      }, 3500);
    }
  };

  const update = (k) => (e) => {
    setForm({ ...form, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value });
    setErrors({ ...errors, [k]: false });
  };

  return (
    <section id="contact" className="section">
      <div className="container contact">
        <SectionHead eyebrow={t.contact.eyebrow} title={t.contact.h} sub={t.contact.sub} align="left" />
        <div className="contact__grid">
          <div className="contact__info">
            <div className="info-block">
              <div className="info-block__label">{t.contact.emailLabel}</div>
              <a className="info-block__v info-block__v--link" href="mailto:hello@x21studio.com">hello@x21studio.com</a>
            </div>
            <div className="info-block">
              <div className="info-block__label">{t.contact.locationLabel}</div>
              <div className="info-block__v">{t.contact.location}</div>
            </div>
            <div className="info-block">
              <div className="info-block__label">{t.contact.responseLabel}</div>
              <div className="info-block__v">{t.contact.response}</div>
            </div>
            <div className="info-block">
              <div className="info-block__label">{t.contact.socialLabel}</div>
              <div className="socials">
                <a href="#" aria-label="Instagram">
                  <svg viewBox="0 0 24 24" width="18" height="18" fill="none">
                    <rect x="3" y="3" width="18" height="18" rx="5" stroke="currentColor" strokeWidth="1.6"/>
                    <circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.6"/>
                    <circle cx="17.5" cy="6.5" r="1" fill="currentColor"/>
                  </svg>
                </a>
                <a href="#" aria-label="LinkedIn">
                  <svg viewBox="0 0 24 24" width="18" height="18" fill="none">
                    <rect x="3" y="3" width="18" height="18" rx="3" stroke="currentColor" strokeWidth="1.6"/>
                    <path d="M 7 10 L 7 17 M 7 7.5 L 7 7.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
                    <path d="M 11 17 L 11 10 M 11 13 Q 11 10 14 10 Q 17 10 17 13 L 17 17" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round"/>
                  </svg>
                </a>
              </div>
            </div>
          </div>

          <form className="contact__form" onSubmit={submit} noValidate>
            <div className={`field ${errors.name ? "is-error" : ""}`}>
              <label>{t.contact.formName} <span className="req">*</span></label>
              <input type="text" value={form.name} onChange={update("name")} />
            </div>
            <div className={`field ${errors.email ? "is-error" : ""}`}>
              <label>{t.contact.formEmail} <span className="req">*</span></label>
              <input type="email" value={form.email} onChange={update("email")} />
            </div>
            <div className="field">
              <label>{t.contact.formCompany}</label>
              <input type="text" value={form.company} onChange={update("company")} />
            </div>
            <div className={`field ${errors.message ? "is-error" : ""}`}>
              <label>{t.contact.formMessage} <span className="req">*</span></label>
              <textarea rows="5" value={form.message} onChange={update("message")} />
            </div>
            <label className={`check ${errors.gdpr ? "is-error" : ""}`}>
              <input type="checkbox" checked={form.gdpr} onChange={update("gdpr")} />
              <span className="check__box" />
              <span className="check__label">
                {t.contact.formGdpr.split("Datenschutzerklärung").length > 1 ? (
                  <>
                    {t.contact.formGdpr.split("Datenschutzerklärung")[0]}
                    <a href="privacy.html" target="_blank">Datenschutzerklärung</a>
                    {t.contact.formGdpr.split("Datenschutzerklärung")[1]}
                  </>
                ) : t.contact.formGdpr.split("privacy policy").length > 1 ? (
                  <>
                    {t.contact.formGdpr.split("privacy policy")[0]}
                    <a href="privacy.html" target="_blank">privacy policy</a>
                    {t.contact.formGdpr.split("privacy policy")[1]}
                  </>
                ) : t.contact.formGdpr}
              </span>
            </label>
            <button type="submit" className="btn btn--gradient btn--lg contact__submit">
              {sent ? t.contact.formSent : t.contact.formSubmit}
            </button>
          </form>
        </div>
      </div>
    </section>
  );
}

// ------------------- Footer -------------------
function Footer({ t, lang, setLang, jump }) {
  return (
    <footer className="footer">
      <div className="container footer__inner">
        <div className="footer__col footer__col--brand">
          <img src="assets/x21-logo.jpeg" alt="x21 Studio" className="footer__logo" />
          <div className="footer__tagline">“{t.footer.tagline}”</div>
          <div className="footer__copy">{t.footer.copyright}</div>
        </div>
        <div className="footer__col">
          <div className="footer__h">{t.footer.navH}</div>
          <ul>
            <li><button onClick={() => jump("services")}>{t.nav.services}</button></li>
            <li><button onClick={() => jump("packages")}>{t.nav.packages}</button></li>
            <li><button onClick={() => jump("transformations")}>{t.nav.transformations}</button></li>
            <li><button onClick={() => jump("about")}>{t.nav.about}</button></li>
            <li><button onClick={() => jump("faq")}>{t.nav.faq}</button></li>
            <li><button onClick={() => jump("contact")}>{t.nav.contact}</button></li>
          </ul>
        </div>
        <div className="footer__col">
          <div className="footer__h">{t.footer.legalH}</div>
          <ul>
            <li><a href="terms.html">{t.footer.terms}</a></li>
            <li><a href="privacy.html">{t.footer.privacy}</a></li>
            <li><a href="#">{t.footer.imprint}</a></li>
          </ul>
        </div>
        <div className="footer__col">
          <div className="footer__h">{t.footer.contactH}</div>
          <ul>
            <li><a href="mailto:hello@x21studio.com">hello@x21studio.com</a></li>
            <li>{t.contact.location}</li>
          </ul>
          <div className="socials socials--footer">
            <a href="#" aria-label="Instagram">
              <svg viewBox="0 0 24 24" width="18" height="18" fill="none">
                <rect x="3" y="3" width="18" height="18" rx="5" stroke="currentColor" strokeWidth="1.6"/>
                <circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.6"/>
                <circle cx="17.5" cy="6.5" r="1" fill="currentColor"/>
              </svg>
            </a>
            <a href="#" aria-label="LinkedIn">
              <svg viewBox="0 0 24 24" width="18" height="18" fill="none">
                <rect x="3" y="3" width="18" height="18" rx="3" stroke="currentColor" strokeWidth="1.6"/>
                <path d="M 7 10 L 7 17" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
                <path d="M 11 17 L 11 10 M 11 13 Q 11 10 14 10 Q 17 10 17 13 L 17 17" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round"/>
              </svg>
            </a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ------------------- Section Head util -------------------
function SectionHead({ eyebrow, title, sub, align = "center" }) {
  return (
    <div className={`section-head section-head--${align}`}>
      <div className="eyebrow"><span className="eyebrow__dot" />{eyebrow}</div>
      <h2 className="section-head__h">{title}</h2>
      {sub && <p className="section-head__sub">{sub}</p>}
    </div>
  );
}

// ------------------- Tweaks panel -------------------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showTransformations": true,
  "gradientStart": "#3B8FD4",
  "gradientEnd": "#8B5CF6",
  "highlightPackage": "standard",
  "heroStyle": "orbs"
}/*EDITMODE-END*/;

function TweaksPanel({ tweaks, setTweaks, visible, t }) {
  if (!visible) return null;
  const upd = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };
  return (
    <div className="tweaks">
      <div className="tweaks__head">
        <div className="tweaks__title">Tweaks</div>
        <div className="tweaks__sub">Live adjustments</div>
      </div>
      <div className="tweaks__body">
        <label className="tweaks__row">
          <span>Show "Brand transformations"</span>
          <input type="checkbox" checked={tweaks.showTransformations} onChange={(e) => upd('showTransformations', e.target.checked)} />
        </label>
        <div className="tweaks__row tweaks__row--col">
          <span>Highlighted package</span>
          <div className="tweaks__seg">
            {['starter','standard','premium'].map(k => (
              <button key={k} className={tweaks.highlightPackage === k ? 'is-on' : ''} onClick={() => upd('highlightPackage', k)}>{k}</button>
            ))}
          </div>
        </div>
        <div className="tweaks__row tweaks__row--col">
          <span>Hero background</span>
          <div className="tweaks__seg">
            {['orbs','minimal','grid'].map(k => (
              <button key={k} className={tweaks.heroStyle === k ? 'is-on' : ''} onClick={() => upd('heroStyle', k)}>{k}</button>
            ))}
          </div>
        </div>
        <div className="tweaks__row">
          <span>Gradient start</span>
          <input type="color" value={tweaks.gradientStart} onChange={(e) => upd('gradientStart', e.target.value)} />
        </div>
        <div className="tweaks__row">
          <span>Gradient end</span>
          <input type="color" value={tweaks.gradientEnd} onChange={(e) => upd('gradientEnd', e.target.value)} />
        </div>
      </div>
    </div>
  );
}

// ------------------- Main App -------------------
function App() {
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem("x21_lang") || "de"; } catch { return "de"; }
  });
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [tweaksOn, setTweaksOn] = useState(false);

  // Edit-mode protocol: register listener FIRST, then announce availability
  useEffect(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksOn(true);
      else if (e.data.type === '__deactivate_edit_mode') setTweaksOn(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  // Apply gradient tweaks as CSS vars
  useEffect(() => {
    document.documentElement.style.setProperty('--grad', `linear-gradient(135deg, ${tweaks.gradientStart} 0%, ${tweaks.gradientEnd} 100%)`);
    document.documentElement.style.setProperty('--blue', tweaks.gradientStart);
    document.documentElement.style.setProperty('--violet', tweaks.gradientEnd);
  }, [tweaks.gradientStart, tweaks.gradientEnd]);

  useEffect(() => {
    document.body.dataset.heroStyle = tweaks.heroStyle;
  }, [tweaks.heroStyle]);

  useEffect(() => {
    try { localStorage.setItem("x21_lang", lang); } catch {}
    document.documentElement.lang = lang;
  }, [lang]);

  const t = window.X21_CONTENT[lang];

  const jump = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  // Scroll-reveal observer
  useEffect(() => {
    const els = document.querySelectorAll("[data-reveal]");
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("is-in");
          obs.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    els.forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, [lang]);

  return (
    <>
      <Nav lang={lang} setLang={setLang} t={t} />
      <main>
        <Hero t={t} jump={jump} />
        <WhatWeDo t={t} />
        <Packages t={t} jump={jump} highlightPackage={tweaks.highlightPackage} />
        {tweaks.showTransformations && <Transformations t={t} />}
        <About t={t} />
        <FAQ t={t} />
        <Contact t={t} />
      </main>
      <Footer t={t} lang={lang} setLang={setLang} jump={jump} />
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} visible={tweaksOn} t={t} />
    </>
  );
}

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