// LUXOMES — Management / Verwaltung page
// Rebuilt 2026-05-16: shifted from investor-focused (new build) to existing-host focused.
// New components: ProcessCircle (replaces RohbauAnimation), TierMatrix (replaces accordion),
// LiveCalculator (replaces static fee example), LeadAnalysis (Formspree-powered free tool).

function MgmtHero({ t, lang }) {
  return (
    <section style={{ paddingTop: 72, paddingBottom: 96 }}>
      <div className="container mgmt-hero">
        <div>
          <div className="eyebrow">{t.mgmt.heroEyebrow}</div>
          <h1 className="h-display" style={{ marginTop: 28, marginBottom: 28, whiteSpace: "pre-line", fontSize: "clamp(40px, 5.4vw, 82px)" }}>{t.mgmt.heroTitle}</h1>
          <p style={{ fontFamily: "var(--font-display)", fontSize: "clamp(22px, 2vw, 30px)", fontStyle: "italic", color: "var(--accent)", marginBottom: 28 }}>{t.mgmt.heroLead}</p>
          <p className="body-lg" style={{ maxWidth: 540, marginBottom: 40 }}>{t.mgmt.heroBody}</p>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            <a href="#mgmt-lead" className="btn btn-primary" onClick={(e) => { e.preventDefault(); document.getElementById("mgmt-lead")?.scrollIntoView({ behavior: "smooth", block: "start" }); }}>
              {t.mgmt.heroCta} <Icon name="arrow" size={16}/>
            </a>
            <button onClick={() => { window.__setPage?.("contact"); window.scrollTo(0,0); }} className="btn btn-ghost">{t.mgmt.heroCtaSecondary}</button>
          </div>
        </div>
        <div style={{ position: "relative" }}>
          <div className="ph" style={{ aspectRatio: "4/5", backgroundImage: `url(${IMG.mgmtHero})`, borderRadius: 4, backgroundSize: "cover", backgroundPosition: "center" }}>
            <SEOImg src={IMG.mgmtHero} alt={lang === "de" ? "Professionelle Verwaltung von Serviced Apartments durch LUXOMES" : "Professional serviced apartment management by LUXOMES"}/>
          </div>
          <div style={{ position: "absolute", top: -24, right: -24, background: "var(--surface)", padding: "20px 24px", boxShadow: "var(--shadow-lift)", border: "1px solid var(--line)", maxWidth: 220 }}>
            <div style={{ fontSize: 12, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 8 }}>{lang === "de" ? "Durchschnittliche Auslastung" : "Average occupancy"}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 36, color: "var(--ink)", lineHeight: 1 }}>75–85%</div>
          </div>
          <div style={{ position: "absolute", bottom: -32, left: -28, background: "var(--ink)", color: "var(--bg)", padding: "20px 24px", maxWidth: 240 }}>
            <div style={{ fontSize: 12, letterSpacing: "0.15em", textTransform: "uppercase", opacity: 0.6, marginBottom: 8 }}>{lang === "de" ? "Eigentümer-Ertrag" : "Owner yield"}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 32, lineHeight: 1 }}>+31%</div>
            <div style={{ fontSize: 12, opacity: 0.7, marginTop: 6 }}>{lang === "de" ? "ggü. Langzeitvermietung" : "vs. long-term rental"}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function MgmtWhySection({ t, lang }) {
  return (
    <section style={{ background: "var(--surface)" }}>
      <div className="container">
        <div className="section-head">
          <div className="section-head-text">
            <Reveal>
              <div className="eyebrow">{t.mgmt.whyEyebrow}</div>
              <h2 className="h-xl" style={{ marginTop: 18, whiteSpace: "pre-line" }}>{t.mgmt.whyTitle}</h2>
            </Reveal>
          </div>
        </div>
        <div className="grid mgmt-why-grid" style={{ gridTemplateColumns: "repeat(2, 1fr)", gap: 1, background: "var(--line)", border: "1px solid var(--line)" }}>
          {MGMT_WHY.map((w, i) => (
            <Reveal key={i} delay={i * 60}>
              <div style={{ background: "var(--surface)", padding: "56px 48px", minHeight: 280, display: "flex", flexDirection: "column", gap: 18 }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 62, color: "var(--accent)", lineHeight: 1, fontWeight: 500 }}>{w.metric}</div>
                <h3 className="h-md">{w.title[lang]}</h3>
                <p className="body-md">{w.body[lang]}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// PROCESS CIRCLE — 6 phases arranged around a circle. Active step expands a detail card.
// Auto-rotation pauses on hover/click. Center shows live metric.
function MgmtProcessCircle({ t, lang }) {
  const [active, setActive] = useState(0);
  const ref = useRef(null);
  const auto = useRef(true);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let timer = null;
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting && auto.current) {
          timer = setInterval(() => {
            if (!auto.current) { clearInterval(timer); return; }
            setActive(p => (p + 1) % MGMT_PROCESS.length);
          }, 3600);
        } else if (timer) {
          clearInterval(timer);
        }
      });
    }, { threshold: 0.3 });
    obs.observe(el);
    return () => { obs.disconnect(); if (timer) clearInterval(timer); };
  }, []);

  // 6 segments around a circle. Step 0 starts at top (12 o'clock).
  const N = MGMT_PROCESS.length;
  const radius = 180;
  const cx = 240, cy = 240;
  const positions = MGMT_PROCESS.map((_, i) => {
    const angle = (i / N) * 2 * Math.PI - Math.PI / 2; // start at 12 o'clock
    return { x: cx + radius * Math.cos(angle), y: cy + radius * Math.sin(angle), angle };
  });

  const iconPath = (name) => {
    const paths = {
      search: <><circle cx="11" cy="11" r="6" fill="none" stroke="currentColor" strokeWidth="1.8"/><line x1="15.5" y1="15.5" x2="20" y2="20" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></>,
      camera: <><rect x="3" y="6" width="18" height="14" rx="2" fill="none" stroke="currentColor" strokeWidth="1.8"/><circle cx="12" cy="13" r="4" fill="none" stroke="currentColor" strokeWidth="1.8"/><rect x="8" y="3" width="8" height="3" fill="currentColor"/></>,
      trending: <><polyline points="3,17 9,11 13,15 21,7" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/><polyline points="16,7 21,7 21,12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></>,
      chat: <><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></>,
      star: <polygon points="12,2 15,8.5 22,9.5 17,14.5 18.5,21.5 12,18 5.5,21.5 7,14.5 2,9.5 9,8.5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>,
      dashboard: <><rect x="3" y="3" width="8" height="8" fill="none" stroke="currentColor" strokeWidth="1.6"/><rect x="13" y="3" width="8" height="5" fill="none" stroke="currentColor" strokeWidth="1.6"/><rect x="13" y="10" width="8" height="11" fill="none" stroke="currentColor" strokeWidth="1.6"/><rect x="3" y="13" width="8" height="8" fill="none" stroke="currentColor" strokeWidth="1.6"/></>,
    };
    return paths[name] || null;
  };

  const cur = MGMT_PROCESS[active];

  return (
    <section ref={ref} style={{ background: "var(--surface)" }}>
      <div className="container">
        <div className="section-head">
          <div className="section-head-text">
            <Reveal>
              <div className="eyebrow">{t.mgmt.processEyebrow}</div>
              <h2 className="h-xl" style={{ marginTop: 18, marginBottom: 22, whiteSpace: "pre-line" }}>{t.mgmt.processTitle}</h2>
              <p className="body-lg" style={{ maxWidth: 640 }}>{t.mgmt.processLead}</p>
            </Reveal>
          </div>
        </div>

        <div className="mgmt-process-grid">
          {/* Circle SVG */}
          <div style={{ position: "relative", aspectRatio: "1/1", maxWidth: 480, width: "100%", margin: "0 auto" }}>
            <svg viewBox="0 0 480 480" style={{ width: "100%", height: "100%", display: "block" }}>
              {/* Outer subtle ring */}
              <circle cx={cx} cy={cy} r={radius + 6} fill="none" stroke="var(--line)" strokeWidth="1"/>
              {/* Animated progress arc */}
              <circle cx={cx} cy={cy} r={radius} fill="none" stroke="var(--accent)" strokeWidth="2"
                strokeDasharray={`${(2 * Math.PI * radius) / N} ${2 * Math.PI * radius}`}
                strokeDashoffset={-(active / N) * 2 * Math.PI * radius + (Math.PI * radius / 2)}
                style={{ transform: "rotate(-90deg)", transformOrigin: `${cx}px ${cy}px`, transition: "stroke-dashoffset .9s cubic-bezier(.65,.05,.36,1)" }}
                strokeLinecap="round"/>
              {/* Inner circle (center metric) */}
              <circle cx={cx} cy={cy} r="98" fill="var(--bg)" stroke="var(--line)" strokeWidth="1"/>
              {/* Center text */}
              <text x={cx} y={cy - 18} fill="var(--muted)" fontSize="11" textAnchor="middle" letterSpacing="2" style={{ textTransform: "uppercase" }}>
                {lang === "de" ? "Phase" : "Phase"} {String(active + 1).padStart(2, "0")} / {String(N).padStart(2, "0")}
              </text>
              <text x={cx} y={cy + 18} fill="var(--accent)" fontSize="34" textAnchor="middle" fontFamily="var(--font-display)">+31%</text>
              <text x={cx} y={cy + 44} fill="var(--ink)" fontSize="11" textAnchor="middle" letterSpacing="1.5" style={{ textTransform: "uppercase" }}>
                {lang === "de" ? "Mehr Umsatz" : "More revenue"}
              </text>

              {/* Step nodes */}
              {positions.map((p, i) => {
                const isActive = i === active;
                return (
                  <g key={i} style={{ cursor: "pointer" }}
                    onMouseEnter={() => { auto.current = false; setActive(i); }}
                    onClick={() => { auto.current = false; setActive(i); }}>
                    {/* Hit area */}
                    <circle cx={p.x} cy={p.y} r="38" fill="transparent"/>
                    {/* Visible node */}
                    <circle cx={p.x} cy={p.y} r={isActive ? 32 : 26}
                      fill={isActive ? "var(--accent)" : "var(--bg)"}
                      stroke={isActive ? "var(--accent)" : "var(--line)"}
                      strokeWidth={isActive ? 0 : 1.5}
                      style={{ transition: "r .35s, fill .35s, stroke .35s, filter .35s", filter: isActive ? "drop-shadow(0 6px 18px oklch(0 0 0 / 0.18))" : "none" }}/>
                    {/* Icon */}
                    <g transform={`translate(${p.x - 12} ${p.y - 12})`} style={{ color: isActive ? "var(--accent-ink)" : "var(--ink)", transition: "color .35s" }}>
                      <svg viewBox="0 0 24 24" width="24" height="24" overflow="visible">{iconPath(MGMT_PROCESS[i].icon)}</svg>
                    </g>
                    {/* Step number */}
                    <circle cx={p.x + 22} cy={p.y - 22} r="10" fill={isActive ? "var(--ink)" : "var(--surface)"} stroke={isActive ? "var(--ink)" : "var(--line)"} strokeWidth="0.8"/>
                    <text x={p.x + 22} y={p.y - 19} fill={isActive ? "var(--bg)" : "var(--ink)"} fontSize="10" textAnchor="middle" fontWeight="600" style={{ transition: "fill .35s" }}>{i + 1}</text>
                  </g>
                );
              })}
            </svg>
          </div>

          {/* Detail card */}
          <div className="mgmt-process-detail">
            <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 20 }}>
              <div style={{ fontSize: 12, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--accent)", fontWeight: 600 }}>
                {lang === "de" ? "Schritt" : "Step"} {String(active + 1).padStart(2, "0")} · {cur.duration[lang]}
              </div>
            </div>
            <h3 className="h-lg" style={{ marginBottom: 18, fontFamily: "var(--font-display)" }}>{cur.title[lang]}</h3>
            <p className="body-lg" style={{ marginBottom: 32 }}>{cur.body[lang]}</p>
            <div style={{ display: "flex", gap: 6, marginBottom: 24 }}>
              {MGMT_PROCESS.map((_, i) => (
                <button key={i}
                  onClick={() => { auto.current = false; setActive(i); }}
                  aria-label={`Step ${i+1}`}
                  style={{
                    flex: 1, height: 4, borderRadius: 2, border: "none", padding: 0,
                    background: i === active ? "var(--accent)" : "var(--line)",
                    cursor: "pointer", transition: "background .35s",
                  }}/>
              ))}
            </div>
            <div style={{ fontSize: 13, color: "var(--muted)" }}>
              {lang === "de" ? "Klick auf die Phasen oder warte — der Kreis rotiert automatisch." : "Click the phases or wait — the circle auto-rotates."}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// SERVICE TIERS — 3 cards (Basic / Plus / Premium) + feature matrix below.
function MgmtTiersSection({ t, lang }) {
  const [activeTier, setActiveTier] = useState("plus"); // default selection = most popular

  return (
    <section>
      <div className="container">
        <div className="section-head">
          <div className="section-head-text">
            <Reveal>
              <div className="eyebrow">{t.mgmt.servicesEyebrow}</div>
              <h2 className="h-xl" style={{ marginTop: 18, marginBottom: 14 }}>{t.mgmt.servicesTitle}</h2>
              <p style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 24, color: "var(--accent)", marginBottom: 20 }}>{t.mgmt.servicesSub}</p>
              <p className="body-lg" style={{ maxWidth: 720 }}>{t.mgmt.servicesLead}</p>
            </Reveal>
          </div>
        </div>

        {/* Tier cards */}
        <div className="mgmt-tier-grid">
          {MGMT_TIERS.map((tier, i) => {
            const isActive = activeTier === tier.key;
            return (
              <Reveal key={tier.key} delay={i * 80} style={{ display: "flex", height: "100%" }}>
                <div
                  onClick={() => setActiveTier(tier.key)}
                  className={"mgmt-tier-card" + (isActive ? " active" : "") + (tier.popular ? " popular" : "")}
                  style={{
                    position: "relative",
                    padding: "44px 36px 36px",
                    background: isActive ? "var(--ink)" : "var(--surface)",
                    color: isActive ? "oklch(0.95 0.005 110)" : "var(--ink)",
                    border: "1px solid " + (isActive ? "var(--ink)" : "var(--line)"),
                    borderRadius: 4,
                    cursor: "pointer",
                    transition: "all .4s cubic-bezier(.65,.05,.36,1)",
                    transform: isActive ? "translateY(-6px)" : "none",
                    boxShadow: isActive ? "0 18px 40px oklch(0 0 0 / 0.18)" : "none",
                    width: "100%",
                    display: "flex", flexDirection: "column",
                  }}>
                  {/* Removed "Beliebtestes Paket" badge — replaced by new section
                      headline "Für jeden das richtige Paket" which conveys the same
                      thought without singling out one tier. */}
                  <div style={{ fontSize: 12, letterSpacing: "0.2em", textTransform: "uppercase", color: isActive ? "var(--accent)" : "var(--muted)", marginBottom: 12, fontWeight: 600 }}>
                    {tier.name[lang]}
                  </div>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 6 }}>
                    <span style={{ fontFamily: "var(--font-display)", fontSize: 72, lineHeight: 1, color: isActive ? "#fff" : "var(--ink)" }}>{tier.fee}</span>
                    <span style={{ fontFamily: "var(--font-display)", fontSize: 36, color: isActive ? "var(--accent)" : "var(--accent)" }}>%</span>
                  </div>
                  <div style={{ fontSize: 13, color: isActive ? "oklch(0.85 0 0)" : "var(--muted)", marginBottom: 24 }}>
                    {lang === "de" ? "vom Netto-Umsatz" : "of net revenue"}
                  </div>
                  <div style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 20, color: isActive ? "var(--accent)" : "var(--accent)", marginBottom: 16 }}>
                    {tier.tagline[lang]}
                  </div>
                  <p style={{ fontSize: 14.5, lineHeight: 1.6, marginBottom: 18, color: isActive ? "oklch(0.92 0 0)" : "var(--ink)" }}>
                    {tier.description[lang]}
                  </p>
                  {/* Highlights — key features visible directly on the card */}
                  <ul style={{ listStyle: "none", padding: 0, margin: "0 0 20px", display: "grid", gap: 9 }}>
                    {tier.highlights[lang].map((h, hi) => (
                      <li key={hi} style={{ display: "flex", gap: 10, fontSize: 13.5, lineHeight: 1.4, color: isActive ? "oklch(0.92 0 0)" : "var(--ink)" }}>
                        <svg viewBox="0 0 24 24" width="16" height="16" style={{ color: "var(--accent)", flexShrink: 0, marginTop: 3 }}>
                          <polyline points="4,12 10,18 20,6" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                        <span>{h}</span>
                      </li>
                    ))}
                  </ul>
                  <div style={{ marginTop: "auto", paddingTop: 18, borderTop: "1px solid " + (isActive ? "oklch(1 0 0 / 0.15)" : "var(--line)") }}>
                    <div style={{ fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", color: isActive ? "var(--accent)" : "var(--muted)", marginBottom: 6 }}>
                      {lang === "de" ? "Ideal für" : "Best for"}
                    </div>
                    <div style={{ fontSize: 13, color: isActive ? "oklch(0.92 0 0)" : "var(--ink)", lineHeight: 1.5 }}>
                      {tier.bestFor[lang]}
                    </div>
                  </div>
                </div>
              </Reveal>
            );
          })}
        </div>

        {/* Feature matrix */}
        <div style={{ marginTop: 80 }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>
            {lang === "de" ? "Vergleich aller Leistungen" : "Compare all features"}
          </div>
          <div className="mgmt-matrix-scroll">
          <div className="mgmt-matrix">
            <div className="mgmt-matrix-head">
              <div className="mgmt-matrix-cell mgmt-matrix-feature-head">
                {lang === "de" ? "Leistung" : "Feature"}
              </div>
              {MGMT_TIERS.map(tier => (
                <div key={tier.key} className={"mgmt-matrix-cell mgmt-matrix-tier-head" + (activeTier === tier.key ? " active" : "")}>
                  <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 4, fontWeight: 600 }}>{tier.name[lang]}</div>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--accent)" }}>{tier.fee}%</div>
                </div>
              ))}
            </div>
            {Object.keys(MGMT_FEATURE_CATS).map(catKey => (
              <div key={catKey}>
                <div className="mgmt-matrix-section-head">
                  {MGMT_FEATURE_CATS[catKey][lang]}
                </div>
                {MGMT_FEATURES.filter(f => f.cat === catKey).map((f, i) => (
                  <div key={i} className="mgmt-matrix-row">
                    <div className="mgmt-matrix-cell mgmt-matrix-feature">{f.title[lang]}</div>
                    {MGMT_TIERS.map(tier => (
                      <div key={tier.key} className={"mgmt-matrix-cell mgmt-matrix-check" + (activeTier === tier.key ? " active" : "")}>
                        {f.included.includes(tier.key) ? (
                          <svg viewBox="0 0 24 24" width="18" height="18" style={{ color: "var(--accent)" }}>
                            <polyline points="4,12 10,18 20,6" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
                          </svg>
                        ) : (
                          <span style={{ color: "var(--line)", fontSize: 18 }}>—</span>
                        )}
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            ))}
          </div>
          </div>
          <p style={{ marginTop: 16, fontSize: 13, color: "var(--muted)", lineHeight: 1.6, maxWidth: 820 }}>
            {MGMT_MATRIX_NOTE[lang]}
          </p>
        </div>
      </div>
    </section>
  );
}

// LIVE CALCULATOR — slider-based revenue projection. Tier × nightly rate × occupancy → owner yield.
function MgmtLiveCalculator({ t, lang }) {
  const [tierKey, setTierKey] = useState("plus");
  const [nightly, setNightly] = useState(120);
  const [occupancy, setOccupancy] = useState(70);

  const tier = MGMT_TIERS.find(t => t.key === tierKey);
  const daysPerMonth = 30;
  const platformFeePct = 12;

  const grossRevenue = nightly * occupancy / 100 * daysPerMonth;
  const platformFee = grossRevenue * platformFeePct / 100;
  const netRevenue = grossRevenue - platformFee;
  const mgmtFee = netRevenue * tier.fee / 100;
  const ownerYield = netRevenue - mgmtFee;
  const longTermComparison = 800; // typical long-term monthly rent for a 1-bedroom — flat assumption

  const fmt = (n) => Math.round(n).toLocaleString(lang === "de" ? "de-DE" : "en-US") + " €";

  return (
    <section style={{ background: "var(--ink)", color: "oklch(0.95 0.005 110)" }}>
      <div className="container">
        <div style={{ marginBottom: 48 }}>
          <div className="eyebrow" style={{ color: "var(--accent)" }}>{t.mgmt.feeEyebrow}</div>
          <h2 className="h-xl" style={{ color: "#fff", marginTop: 18, marginBottom: 18 }}>{t.mgmt.feeTitle}</h2>
          <p className="body-lg" style={{ color: "oklch(0.85 0 0)", maxWidth: 620 }}>{t.mgmt.feeLead}</p>
        </div>

        <div className="mgmt-calc-grid">
          {/* Controls */}
          <div className="mgmt-calc-controls">
            {/* Tier selector */}
            <div style={{ marginBottom: 36 }}>
              <div style={{ fontSize: 12, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 14, fontWeight: 600 }}>
                {lang === "de" ? "Dein Paket" : "Your tier"}
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
                {MGMT_TIERS.map(t => (
                  <button key={t.key}
                    onClick={() => setTierKey(t.key)}
                    style={{
                      padding: "14px 8px", textAlign: "center",
                      background: tierKey === t.key ? "var(--accent)" : "transparent",
                      color: tierKey === t.key ? "var(--accent-ink)" : "#fff",
                      border: "1px solid " + (tierKey === t.key ? "var(--accent)" : "oklch(1 0 0 / 0.15)"),
                      cursor: "pointer", transition: "all .3s", borderRadius: 2,
                    }}>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 22, lineHeight: 1 }}>{t.fee}%</div>
                    <div style={{ fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", marginTop: 4, opacity: tierKey === t.key ? 1 : 0.7 }}>{t.name[lang]}</div>
                  </button>
                ))}
              </div>
            </div>

            {/* Nightly rate slider */}
            <div style={{ marginBottom: 36 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
                <span style={{ fontSize: 12, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--accent)", fontWeight: 600 }}>
                  {lang === "de" ? "Ø Nachtpreis" : "Avg nightly rate"}
                </span>
                <span style={{ fontFamily: "var(--font-display)", fontSize: 28, color: "#fff" }}>{nightly} €</span>
              </div>
              <input type="range" min="50" max="500" step="5" value={nightly} onChange={e => setNightly(Number(e.target.value))} className="mgmt-slider" />
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "oklch(0.6 0 0)", marginTop: 6 }}>
                <span>50 €</span><span>500 €</span>
              </div>
            </div>

            {/* Occupancy slider */}
            <div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
                <span style={{ fontSize: 12, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--accent)", fontWeight: 600 }}>
                  {lang === "de" ? "Auslastung" : "Occupancy"}
                </span>
                <span style={{ fontFamily: "var(--font-display)", fontSize: 28, color: "#fff" }}>{occupancy}%</span>
              </div>
              <input type="range" min="30" max="95" step="1" value={occupancy} onChange={e => setOccupancy(Number(e.target.value))} className="mgmt-slider" />
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "oklch(0.6 0 0)", marginTop: 6 }}>
                <span>30%</span><span>95%</span>
              </div>
            </div>
          </div>

          {/* Output */}
          <div className="mgmt-calc-output">
            <div style={{ fontSize: 12, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 24, fontWeight: 600 }}>
              {lang === "de" ? "Dein Ergebnis · pro Monat" : "Your result · per month"}
            </div>

            <CalcRow label={lang === "de" ? "Bruttoumsatz (30 Tage)" : "Gross revenue (30 days)"} value={fmt(grossRevenue)} />
            <CalcRow label={lang === "de" ? `Portal-Gebühren (~${platformFeePct}%)` : `Portal fees (~${platformFeePct}%)`} value={"−" + fmt(platformFee)} muted />
            <CalcRow label={lang === "de" ? "Netto-Umsatz" : "Net revenue"} value={fmt(netRevenue)} subtle />
            <CalcRow label={lang === "de" ? `LUXOMES (${tier.fee}%)` : `LUXOMES (${tier.fee}%)`} value={"−" + fmt(mgmtFee)} muted />

            <div style={{ marginTop: 22, padding: "26px 28px", background: "var(--accent)", color: "var(--accent-ink)", borderRadius: 4 }}>
              <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: 8, fontWeight: 600 }}>
                {lang === "de" ? "Dein Reingewinn" : "Your net yield"}
              </div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 56, lineHeight: 1 }}>
                <AnimatedNumber value={Math.round(ownerYield)} suffix=" €" />
              </div>
              <div style={{ fontSize: 13, marginTop: 10, opacity: 0.8 }}>
                {lang === "de" ? `Langzeitvermietung: ~${fmt(longTermComparison)}/Monat` : `Long-term let: ~${fmt(longTermComparison)}/month`} · <strong>+{Math.round(((ownerYield - longTermComparison) / longTermComparison) * 100)}%</strong>
              </div>
            </div>

            <div style={{ marginTop: 20, fontSize: 12, color: "oklch(0.65 0 0)", lineHeight: 1.6 }}>
              {lang === "de" ? "* Berechnung auf Basis 30 Tage/Monat und ~12% durchschnittlicher Portal-Provision. Tatsächliche Werte abhängig von Standort, Saisonalität und Buchungs-Mix." : "* Based on 30 days/month and ~12% average portal commission. Actual values vary by location, seasonality and booking mix."}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function CalcRow({ label, value, muted, subtle }) {
  return (
    <div style={{
      display: "flex", justifyContent: "space-between", alignItems: "baseline",
      padding: "14px 0",
      borderBottom: subtle ? "1px solid oklch(1 0 0 / 0.1)" : "none",
    }}>
      <span style={{ fontSize: 14, color: muted ? "oklch(0.65 0 0)" : "oklch(0.92 0 0)" }}>{label}</span>
      <span style={{ fontFamily: "var(--font-display)", fontSize: subtle ? 24 : 18, color: subtle ? "#fff" : "oklch(0.85 0 0)", fontWeight: subtle ? 500 : 400 }}>
        {value}
      </span>
    </div>
  );
}

// Animated counter — smoothly tweens to the target value.
function AnimatedNumber({ value, suffix = "" }) {
  const [display, setDisplay] = useState(value);
  const fromRef = useRef(value);
  const startRef = useRef(Date.now());

  useEffect(() => {
    fromRef.current = display;
    startRef.current = Date.now();
    const duration = 500;
    let raf = null;
    const tick = () => {
      const elapsed = Date.now() - startRef.current;
      const t = Math.min(1, elapsed / duration);
      const eased = 1 - Math.pow(1 - t, 3); // easeOutCubic
      const cur = Math.round(fromRef.current + (value - fromRef.current) * eased);
      setDisplay(cur);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line
  }, [value]);

  return <>{display.toLocaleString("de-DE")}{suffix}</>;
}

// LEAD-GEN — Instant heuristic estimator + Formspree contact form.
// The estimate uses hardcoded city benchmarks (MGMT_CITY_BENCHMARKS) — no external API,
// no fake AI claims. Honest copy: "based on city benchmarks, full report in 24h".
function MgmtLeadAnalysis({ t, lang }) {
  const [formData, setFormData] = useState({ address: "", size: "", status: "", email: "", phone: "" });
  const [state, setState] = useState("idle"); // idle | submitting | success | error
  const [estimate, setEstimate] = useState(null);

  // Pure heuristic: city benchmark × sqm scale → monthly range.
  // Premium tier (25%) assumed. Platform fees ~12%. No AirDNA, no AI — just transparent math.
  const computeEstimate = () => {
    const sizeRaw = parseInt(String(formData.size).replace(/[^\d]/g, ""), 10);
    if (!formData.address || !sizeRaw || sizeRaw < 15) return null;
    const bench = mgmtFindBenchmark(formData.address);
    const sizeFactor = Math.min(Math.max(sizeRaw / bench.m2Reference, 0.65), 2.2); // clamp to reasonable bounds
    const grossLow  = bench.nightlyLow  * (bench.occupancyLow  / 100) * 30 * sizeFactor;
    const grossHigh = bench.nightlyHigh * (bench.occupancyHigh / 100) * 30 * sizeFactor;
    const platformFee = 0.12; const mgmtFee = 0.25; // Premium tier as basis
    const netLow  = grossLow  * (1 - platformFee) * (1 - mgmtFee);
    const netHigh = grossHigh * (1 - platformFee) * (1 - mgmtFee);
    return {
      city: bench.label,
      sqm: sizeRaw,
      low: Math.round(netLow / 50) * 50,    // round to nearest 50€
      high: Math.round(netHigh / 50) * 50,
    };
  };

  // Recompute estimate when address or size changes.
  useEffect(() => {
    const e = computeEstimate();
    setEstimate(e);
    // eslint-disable-next-line
  }, [formData.address, formData.size]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.address || !formData.email) return;
    setState("submitting");
    // Use the shared submitContact helper — it has the placeholder guard
    // (skips POST when Formspree endpoint is still "YOUR_FORM_ID") and honeypot logic.
    const result = await window.submitContact(e.target, {
      _subject: `[LUXOMES] Kostenlose Objekt-Analyse: ${formData.address}`,
      topic: lang === "de" ? "Kostenlose Potenzial-Analyse" : "Free potential analysis",
      source: "management-lead-analysis",
      instant_estimate: estimate ? `${estimate.low}–${estimate.high} €/Monat (${estimate.city}, ${estimate.sqm}m²)` : "n/a",
    });
    if (result.ok) {
      setState("success");
      setFormData({ address: "", size: "", status: "", email: "", phone: "" });
      setEstimate(null);
    } else {
      setState("error");
    }
  };

  const fmt = (n) => Math.round(n).toLocaleString(lang === "de" ? "de-DE" : "en-US") + " €";

  return (
    <section id="mgmt-lead" style={{ background: "var(--surface)" }}>
      <div className="container">
        <div className="mgmt-lead-grid">
          <div>
            <div className="eyebrow">{t.mgmt.leadEyebrow}</div>
            <h2 className="h-xl" style={{ marginTop: 18, marginBottom: 22 }}>{t.mgmt.leadTitle}</h2>
            <p className="body-lg" style={{ marginBottom: 32, maxWidth: 520 }}>{t.mgmt.leadLead}</p>

            {/* Live estimate appears here as soon as city + size are entered */}
            {estimate ? (
              <div className="mgmt-estimate-box">
                <div className="mgmt-estimate-eyebrow">{t.mgmt.leadEstimateLabel}</div>
                <div className="mgmt-estimate-value">
                  <AnimatedNumber value={estimate.low} suffix="" /> – <AnimatedNumber value={estimate.high} suffix=" €" />
                </div>
                <div className="mgmt-estimate-meta">
                  <span>{t.mgmt.leadEstimateBasis}: {estimate.city} · {estimate.sqm} m² · Premium-Tier 25%</span>
                </div>
                <div className="mgmt-estimate-hint">{t.mgmt.leadEstimateHint}</div>
              </div>
            ) : (
              <div style={{ display: "grid", gap: 20 }}>
                <LeadBenefit num="60s" label={lang === "de" ? "Sofort-Schätzung" : "Instant estimate"} body={lang === "de" ? "Gib Stadt + m² ein — Du siehst sofort eine Range basierend auf unseren Stadt-Benchmarks." : "Enter city + sqm — see an instant range based on our city benchmarks."}/>
                <LeadBenefit num="24h" label={lang === "de" ? "Detail-Bericht persönlich" : "Detail report, personal"} body={lang === "de" ? "Adress-spezifische Analyse mit Saisonalität und Wettbewerb vom Team." : "Address-specific analysis with seasonality and competition, from the team."}/>
                <LeadBenefit num="0 €" label={lang === "de" ? "Kostenlos & unverbindlich" : "Free & non-binding"} body={lang === "de" ? "Auch wenn Du nichts buchst: Du behältst den Bericht." : "Even if you don't book anything: the report stays yours."}/>
              </div>
            )}
          </div>

          <form onSubmit={handleSubmit} style={{ padding: 40, background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 4 }}>
            {state === "success" ? (
              <div style={{ textAlign: "center", padding: "60px 20px" }}>
                <div style={{
                  width: 72, height: 72, margin: "0 auto 24px",
                  borderRadius: "50%", background: "var(--accent)",
                  display: "grid", placeItems: "center",
                }}>
                  <svg viewBox="0 0 24 24" width="32" height="32" style={{ color: "var(--accent-ink)" }}>
                    <polyline points="4,12 10,18 20,6" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
                <h3 className="h-md" style={{ marginBottom: 12 }}>{lang === "de" ? "Anfrage erhalten!" : "Request received!"}</h3>
                <p className="body-md">{t.mgmt.leadFormSuccess}</p>
              </div>
            ) : (
              <>
                <div style={{ marginBottom: 22 }}>
                  <label className="form-label">{t.mgmt.leadFormAddress} *</label>
                  <input type="text" required value={formData.address} onChange={e => setFormData({...formData, address: e.target.value})} className="form-input" placeholder={lang === "de" ? "z.B. Nürnberg oder Hauptstr. 12, Ingolstadt" : "e.g. Nuremberg or Main St 12, Ingolstadt"}/>
                </div>
                <div style={{ marginBottom: 22 }}>
                  <label className="form-label">{t.mgmt.leadFormSize}</label>
                  <input type="text" value={formData.size} onChange={e => setFormData({...formData, size: e.target.value})} className="form-input" placeholder={lang === "de" ? "z.B. 65" : "e.g. 65"} inputMode="numeric"/>
                </div>
                <div style={{ marginBottom: 22 }}>
                  <label className="form-label">{t.mgmt.leadFormStatus}</label>
                  <select value={formData.status} onChange={e => setFormData({...formData, status: e.target.value})} className="form-input">
                    <option value="">{lang === "de" ? "Bitte wählen…" : "Please select…"}</option>
                    {t.mgmt.leadFormStatusOpts.map((opt, i) => (
                      <option key={i} value={opt}>{opt}</option>
                    ))}
                  </select>
                </div>
                <div style={{ marginBottom: 22 }}>
                  <label className="form-label">{t.mgmt.leadFormEmail} *</label>
                  <input type="email" required value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})} className="form-input"/>
                </div>
                <div style={{ marginBottom: 28 }}>
                  <label className="form-label">{t.mgmt.leadFormPhone}</label>
                  <input type="tel" value={formData.phone} onChange={e => setFormData({...formData, phone: e.target.value})} className="form-input"/>
                </div>
                <button type="submit" disabled={state === "submitting"} className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }}>
                  {state === "submitting" ? (lang === "de" ? "Sende…" : "Sending…") : t.mgmt.leadFormSubmit} <Icon name="arrow" size={16}/>
                </button>
                {state === "error" && (
                  <div style={{ marginTop: 16, padding: 14, background: "oklch(0.92 0.08 30)", color: "oklch(0.4 0.15 30)", fontSize: 13, borderRadius: 2 }}>
                    {lang === "de" ? "Etwas ist schiefgelaufen. Bitte erneut versuchen oder direkt an info@luxomes.com schreiben." : "Something went wrong. Please retry or email info@luxomes.com directly."}
                  </div>
                )}
                <p style={{ fontSize: 12, color: "var(--muted)", marginTop: 16, lineHeight: 1.5 }}>{t.mgmt.leadFormPromise}</p>
              </>
            )}
          </form>
        </div>
      </div>
    </section>
  );
}

function LeadBenefit({ num, label, body }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "80px 1fr", gap: 20, alignItems: "baseline" }}>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 38, color: "var(--accent)", lineHeight: 1 }}>{num}</div>
      <div>
        <div style={{ fontWeight: 600, marginBottom: 4, fontSize: 15 }}>{label}</div>
        <div style={{ fontSize: 14, color: "var(--muted)", lineHeight: 1.55 }}>{body}</div>
      </div>
    </div>
  );
}

function MgmtModulesSection({ t, lang }) {
  return (
    <section>
      <div className="container">
        <div className="section-head">
          <div className="section-head-text">
            <Reveal>
              <div className="eyebrow">{t.mgmt.modulesEyebrow}</div>
              <h2 className="h-xl" style={{ marginTop: 18, marginBottom: 22 }}>{t.mgmt.modulesTitle}</h2>
              <p className="body-lg">{t.mgmt.modulesLead}</p>
            </Reveal>
          </div>
        </div>
        <div className="grid mgmt-modules-grid" style={{ gridTemplateColumns: "repeat(2, 1fr)", gap: 24 }}>
          {MGMT_MODULES.map((m, i) => (
            <Reveal key={i} delay={i * 50}>
              <div style={{
                padding: 36, border: "1px solid var(--line)", borderRadius: 4, minHeight: 220,
                display: "flex", flexDirection: "column", background: m.free ? "var(--ink)" : "var(--surface)",
                color: m.free ? "oklch(0.95 0.005 110)" : "var(--ink)",
                position: "relative",
              }}>
                {m.free && (
                  <div style={{ position: "absolute", top: 16, right: 16, background: "var(--accent)", color: "var(--accent-ink)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", padding: "5px 10px", fontWeight: 700, borderRadius: 2 }}>
                    {lang === "de" ? "Kostenlos" : "Free"}
                  </div>
                )}
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16, gap: 20 }}>
                  <h3 className="h-md" style={{ maxWidth: "70%", color: m.free ? "#fff" : "var(--ink)" }}>{m.title[lang]}</h3>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "var(--accent)", whiteSpace: "nowrap" }}>{m.price[lang]}</div>
                </div>
                <p style={{ fontSize: 14.5, lineHeight: 1.65, marginBottom: m.free ? 20 : "auto", color: m.free ? "oklch(0.88 0 0)" : "var(--ink)" }}>{m.body[lang]}</p>
                {m.free && (
                  <a href="#mgmt-lead"
                    onClick={(e) => { e.preventDefault(); document.getElementById("mgmt-lead")?.scrollIntoView({ behavior: "smooth", block: "start" }); }}
                    className="btn btn-primary" style={{ alignSelf: "flex-start", marginTop: "auto" }}>
                    {lang === "de" ? "Jetzt anfragen" : "Request now"} <Icon name="arrow" size={16}/>
                  </a>
                )}
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function MgmtFinalCTA({ t, lang, setPage }) {
  return (
    <section style={{ padding: 0 }}>
      <div className="container">
        <div style={{ position: "relative", padding: "120px 64px", overflow: "hidden", borderRadius: 4 }}>
          <div className="ph" style={{ position: "absolute", inset: 0, backgroundImage: `url(${IMG.interior5})`, backgroundSize: "cover", backgroundPosition: "center" }}/>
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(120deg, oklch(0 0 0 / 0.7), oklch(0 0 0 / 0.3))" }}/>
          <div style={{ position: "relative", color: "#fff", maxWidth: 720 }}>
            <h2 className="h-xl" style={{ color: "#fff", marginBottom: 24, whiteSpace: "pre-line" }}>{t.mgmt.finalTitle}</h2>
            <p className="body-lg" style={{ color: "oklch(0.92 0 0)", marginBottom: 36 }}>{t.mgmt.finalText}</p>
            <button onClick={() => { setPage("contact"); window.scrollTo(0,0); }} className="btn btn-primary">{t.mgmt.finalCta} <Icon name="arrow" size={16}/></button>
          </div>
        </div>
      </div>
    </section>
  );
}

function ManagementPage({ t, lang, tweaks, setPage }) {
  return (
    <>
      <MgmtHero t={t} lang={lang}/>
      <MgmtWhySection t={t} lang={lang}/>
      <MgmtProcessCircle t={t} lang={lang}/>
      <MgmtTiersSection t={t} lang={lang}/>
      <MgmtLiveCalculator t={t} lang={lang}/>
      <MgmtLeadAnalysis t={t} lang={lang}/>
      <CaseStudySection slug="aparthotel-takeover" lang={lang} setPage={setPage}/>
      <MgmtModulesSection t={t} lang={lang}/>
      <MgmtFinalCTA t={t} lang={lang} setPage={setPage}/>
    </>
  );
}

Object.assign(window, { ManagementPage });
