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

// --- Branchen-Werte ---
const BRANCHEN = [
  { key: "baeckerei", label: "Bäckerei" },
  { key: "mode",      label: "Mode" },
  { key: "beauty",    label: "Dienstleistung / Beauty" },
  { key: "apotheke",  label: "Apotheke" },
  { key: "gastro",    label: "Gastronomie" },
  { key: "sonstige",  label: "Sonstige" },
];

// --- Formatter (europäisch) ---
const euro = (n) => new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }).format(Math.round(n || 0));
const num = (n) => new Intl.NumberFormat("de-DE").format(Math.round(n || 0));

function getPrice(plan, users) {
  if (plan === "pro" || plan === "enterprise") return null;
  if (users > 6000) return null;

  if (plan === "starter") {
    if (users <= 1000) return 449;
    if (users <= 1500) return 545;
    if (users <= 2000) return 630;
    if (users <= 3000) return 760;
    if (users <= 4000) return 866;
    if (users <= 5000) return 951;
    if (users <= 6000) return 1016;
  }
  if (plan === "plus") {
    if (users <= 1000) return 556;
    if (users <= 1500) return 683;
    if (users <= 2000) return 780;
    if (users <= 3000) return 951;
    if (users <= 4000) return 1091;
    if (users <= 5000) return 1187;
    if (users <= 6000) return 1273;
  }
  return null;
}

// A single flowing brand line that makes real LOOPS.
function randomRibbon() {
  const W = 1000, H = 260, pad = 24;
  const loops = [1, 1, 2, 2, 3][Math.floor(Math.random() * 5)];
  const a = 1;
  const b = 1.95 + Math.random() * 0.7;
  const ySign = Math.random() < 0.5 ? 1 : -1;
  const slope = (Math.random() - 0.5) * 0.22;
  const span = loops * 2 * Math.PI;
  const t0 = Math.PI;
  const steps = Math.max(90, loops * 80);

  const raw = [];
  for (let i = 0; i <= steps; i++) {
    const t = t0 + (i / steps) * span;
    const x = a * t - b * Math.sin(t);
    const y = ySign * (-b * Math.cos(t)) + slope * t;
    raw.push([x, y]);
  }

  let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
  for (const [x, y] of raw) {
    if (x < minX) minX = x; if (x > maxX) maxX = x;
    if (y < minY) minY = y; if (y > maxY) maxY = y;
  }
  const s = Math.min((W - 2 * pad) / (maxX - minX || 1), (H - 2 * pad) / (maxY - minY || 1));
  const offX = (W - (maxX - minX) * s) / 2 - minX * s;
  const offY = (H - (maxY - minY) * s) / 2 - minY * s;
  const sp = raw.map(([x, y]) => [x * s + offX, y * s + offY]);
  const n = sp.length;
  
  const extend = (pA, pB, targetX) => {
    let dx = pA[0] - pB[0], dy = pA[1] - pB[1];
    const len = Math.hypot(dx, dy) || 1; dx /= len; dy /= len;
    let m = 700;
    if (Math.abs(dx) > 0.05) m = Math.max(m, (targetX - pA[0]) / dx);
    return [pA[0] + dx * m, pA[1] + dy * m];
  };
  const lead0 = extend(sp[0], sp[1], -300);
  const leadN = extend(sp[n - 1], sp[n - 2], W + 300);
  const pts = [lead0, ...sp, leadN];
  let d = "";
  pts.forEach(([x, y], i) => {
    d += (i === 0 ? "M" : "L") + x.toFixed(1) + "," + y.toFixed(1) + " ";
  });

  const top = 2 + Math.random() * 66;
  const left = -(22 + Math.random() * 22);
  const width = 146 + Math.random() * 40;
  const rot = -5 + Math.random() * 10;
  const sc = 0.82 + Math.random() * 0.3;
  const opacity = 0.16 + Math.random() * 0.14;
  const dur = (9 + Math.random() * 3.5).toFixed(1) + "s";
  return {
    d: d.trim(),
    dur,
    style: {
      top: top + "%", left: left + "%", width: width + "%", opacity,
      transform: "rotate(" + rot.toFixed(1) + "deg) scale(" + sc.toFixed(2) + ")",
    },
  };
}

function SingleRibbon() {
  const [r, setR] = useState(() => ({ ...randomRibbon(), delay: "-2s" }));
  const pathRef = useRef(null);
  useEffect(() => {
    const el = pathRef.current;
    if (!el) return;
    const onIter = () => setR(randomRibbon());
    el.addEventListener("animationiteration", onIter);
    return () => el.removeEventListener("animationiteration", onIter);
  }, []);
  return (
    <svg className="ribbon" viewBox="0 0 1000 260" fill="none" aria-hidden="true" style={r.style}>
      <defs>
        <linearGradient id="rgrad" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0" stopColor="#00A7E1" />
          <stop offset="1" stopColor="#8BC753" />
        </linearGradient>
      </defs>
      <path
        ref={pathRef}
        className="ribbon-path"
        pathLength="1000"
        stroke="url(#rgrad)"
        strokeWidth="1.7"
        strokeLinecap="round"
        strokeLinejoin="round"
        d={r.d}
        style={{ animationDuration: r.dur, animationDelay: r.delay || "0s" }}
      />
    </svg>
  );
}

const PLANS = [
  { key: "starter", label: "Starter" },
  { key: "plus", label: "Plus" },
  { key: "pro", label: "Pro" },
  { key: "enterprise", label: "Enterprise" },
];

const PLAN_FEATURES = {
  starter: [
    "App für iOS & Android",
    "Treueclub für deine Kund:innen",
    "Automatisierte Push-Nachrichten, Mail & SMS",
    "Neukundengewinnung",
    "Integrierte Kundendatenbank (CRM)",
    "Analysen des Kundenverhaltens",
    "und vieles mehr."
  ],
  plus: [
    "Alle Starter-Funktionen",
    "Onlineshop-Integration",
    "Ranglisten & Statuslevels",
    "Kundenbewertungen auf Plattformen wie Google",
    "Umfragen & Feedback",
    "und vieles mehr."
  ],
  pro: [
    "Alle Plus-Funktionen",
    "Mehrsprachigkeit",
    "Digitale Rechnungsablage",
    "Digitaler Sammelpass",
    "Loyalty Web Portal",
    "und vieles mehr."
  ],
  enterprise: [
    "Alle Pro-Funktionen",
    "Individuell auf Wünsche & Bedürfnisse abgestimmt",
    "Betreuung durch Projektmanager:in"
  ]
};

const PLAN_UPLIFTS = {
  starter: "+15% durchschnittlicher Warenkorbwert bei der Bäckerei Kühl",
  plus: "2.000 Registrierungen in 6 Monaten bei der Apotheke Mariahilf",
  pro: "+100% Kundenfrequenz bei Nutzer:innen bei figarouno",
  enterprise: "1 Mio. Registrierungen in 6 Monaten bei Müller"
};

function App() {
  const [plan, setPlan] = useState("starter");
  const [stammkunden, setStammkunden] = useState(1000);

  const price = getPrice(plan, stammkunden);

  return (
    <React.Fragment>
      <header className="hero-band" id="preis">
        <div className="hero-deco" aria-hidden="true">
          <span className="aurora a"></span>
          <span className="aurora b"></span>
          <span className="aurora c"></span>
        </div>

        <div className="topbar">
          <a className="brand" href="#" aria-label="hello again">
            <img className="logo-light" src="assets/logo-primary.svg" alt="hello again" />
            <img className="logo-dark" src="assets/logo-negative-lockup.png" alt="hello again" />
          </a>
          <nav style={{ display: "flex", gap: 24, alignItems: "center" }}>
            <a href="#preis" style={{ color: "rgba(255,255,255,0.8)", textDecoration: "none", fontSize: 14, fontWeight: 700 }}>Preis</a>
            <a href="#addons" style={{ color: "rgba(255,255,255,0.8)", textDecoration: "none", fontSize: 14, fontWeight: 700 }}>Add-Ons</a>
          </nav>
        </div>

        <div className="hero-inner">
          <div className="hero-copy" style={{ textAlign: "center", maxWidth: 800, margin: "0 auto 48px" }}>
            <p className="eyebrow">Transparente Preise</p>
            <h1 className="hero">
              Berechne den Preis deiner <span className="ha-accent">Loyalty-Lösung</span>
            </h1>
            <p className="hero-sub" style={{ margin: "0 auto" }}>
              Wähle die Anzahl deiner Stammkunden, um einen ersten Richtwert für deine Investition zu erhalten.
            </p>
          </div>

          <div className="step1">
            <div className="card input-card" style={{ margin: 0 }}>
              <div className="field">
                <label>Wähle einen Plan:</label>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {PLANS.map((p) => (
                    <button
                      type="button"
                      key={p.key}
                      onClick={() => setPlan(p.key)}
                      style={{
                        padding: "8px 16px",
                        borderRadius: "99px",
                        border: plan === p.key ? "2px solid var(--ha-smart)" : "1px solid var(--ha-line)",
                        background: plan === p.key ? "rgba(0,167,225,.1)" : "#fff",
                        color: plan === p.key ? "var(--ha-smart-mid)" : "var(--fg-1)",
                        cursor: "pointer",
                        fontWeight: plan === p.key ? 700 : 400,
                        fontSize: 14
                      }}
                    >
                      {p.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="field" style={{ marginTop: 24 }}>
                <label>Anzahl deiner Stammkund:innen (gesamt): {num(stammkunden)}</label>
                <input
                  className="slider"
                  type="range"
                  min="0"
                  max="10000"
                  step="100"
                  value={stammkunden}
                  onChange={(e) => setStammkunden(Number(e.target.value))}
                  style={{ background: `linear-gradient(to right, var(--ha-smart) ${(stammkunden / 10000) * 100}%, var(--ha-surface-2) ${(stammkunden / 10000) * 100}%)` }}
                />
                <div className="scale-ticks">
                  <span>0</span><span>5.000</span><span>10.000</span>
                </div>
              </div>

              <div style={{ marginTop: 32, textAlign: "center" }}>
                {price !== null ? (
                  <React.Fragment>
                    <div style={{ fontSize: 14, color: "var(--fg-2)", marginBottom: 8 }}>Exemplarischer Preis pro Monat*</div>
                    <div style={{ fontSize: 48, fontWeight: 700, fontFamily: "var(--font-display)", color: "var(--ha-smart-mid)", marginBottom: 24 }}>
                      {euro(price)}
                    </div>
                    <a href={`https://www.helloagain.com/de/anfrage?wunschplan=${plan}&durchschnittspreis=${price}&stammkundenanzahl=${stammkunden}`} className="btn btn-primary btn-block" style={{ textDecoration: "none" }}>
                      Tatsächlichen Preis anfragen
                    </a>
                  </React.Fragment>
                ) : (
                  <React.Fragment>
                    <div style={{ fontSize: 14, color: "var(--fg-2)", marginBottom: 8 }}>Individueller Preis</div>
                    <div style={{ fontSize: 24, fontWeight: 700, fontFamily: "var(--font-display)", color: "var(--ha-smart-mid)", marginBottom: 24, lineHeight: 1.3 }}>
                      Lass uns gemeinsam das perfekte Setup für dich besprechen.
                    </div>
                    <a href="https://www.helloagain.com/de/termin" className="btn btn-primary btn-block" style={{ textDecoration: "none" }}>
                      Termin buchen
                    </a>
                  </React.Fragment>
                )}
                <div style={{ marginTop: 16, fontSize: 12, color: "var(--fg-3)", lineHeight: 1.4, textAlign: "center" }}>
                  * Dies ist nur ein Richtwert. Der tatsächliche Preis hängt von deinen individuellen Gegebenheiten und Anforderungen ab. Preisangabe exklusive optionaler Addongebühren oder zusätzlichen Gebühren für Integrationen.
                </div>
              </div>
            </div>

            <div className="card features-card" style={{ background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", color: "#fff", margin: 0 }}>
              <h2 style={{ fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 700, marginBottom: 24 }}>
                Inkludierte Features im {PLANS.find(p => p.key === plan).label}-Plan
              </h2>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 16 }}>
                {PLAN_FEATURES[plan].map((feature, idx) => (
                  <li key={idx} style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 16 }}>
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--ha-smart-mid)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
                      <polyline points="20 6 9 17 4 12"></polyline>
                    </svg>
                    {feature}
                  </li>
                ))}
              </ul>
              <div style={{ marginTop: 32, padding: 16, background: "rgba(0,167,225,0.15)", borderRadius: 8, borderLeft: "4px solid var(--ha-smart-mid)" }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ha-smart-mid)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.05em" }}>Erfolge unserer Kunden</div>
                <div style={{ fontSize: 15, lineHeight: 1.4 }}>{PLAN_UPLIFTS[plan]}</div>
              </div>
            </div>
          </div>
        </div>
      </header>

      <section id="addons" style={{ padding: "96px 24px", background: "var(--bg-page)", color: "var(--fg-1)" }}>
        <div style={{ maxWidth: 940, margin: "0 auto" }}>
          <div style={{ textAlign: "center", marginBottom: 48 }}>
            <h2 style={{ fontFamily: "var(--font-display)", fontSize: 32, fontWeight: 700, marginBottom: 16 }}>Optionale <span className="ha-accent">Erweiterungen</span></h2>
            <p style={{ fontSize: 16, color: "var(--fg-2)", maxWidth: 600, margin: "0 auto", lineHeight: 1.5 }}>
              Wir bieten flexible Add-Ons und nahtlose Integrationen in deine bestehenden Systeme. Da diese individuell auf deine Bedürfnisse abgestimmt werden, besprechen wir die Details und Preise hierfür am besten in einem persönlichen Gespräch.
            </p>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 32 }}>
            <div className="card addon-card" style={{ display: "flex", flexDirection: "column" }}>
              <h3 className="h3" style={{ marginBottom: 12, color: "var(--ha-smart-mid)" }}>Add-Ons</h3>
              <p className="body" style={{ marginBottom: 16 }}>
                Erweitere deine App um spannende Funktionen wie Gamification (z.B. Glücksrad, Rubbellose) oder spezielle Module für Mitarbeiter-Incentives.
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12, fontSize: "var(--fs-body)", color: "var(--fg-1)" }}>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> Games Subscription Package (inkl. App Banner)</li>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> Glücksrad (inkl. App Banner)</li>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> Stempelpass</li>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> Guthabenskarte und Geschenkgutscheine</li>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> Mitarbeiterbereich</li>
              </ul>
              <div style={{ marginTop: "auto", paddingTop: 24 }}>
                <a href="https://www.helloagain.com/de/termin" style={{ color: "var(--ha-smart-mid)", textDecoration: "none", fontWeight: 700, fontSize: "var(--fs-body)", display: "flex", alignItems: "center", gap: 4 }}>
                  Termin vereinbaren <span aria-hidden="true">→</span>
                </a>
              </div>
            </div>
            <div className="card addon-card" style={{ display: "flex", flexDirection: "column" }}>
              <h3 className="h3" style={{ marginBottom: 12, color: "var(--ha-smart-mid)" }}>Integrationen</h3>
              <p className="body" style={{ marginBottom: 16 }}>
                Verbinde deine Loyalty-App nahtlos mit deinen bestehenden Systemen. Wir bieten Schnittstellen zu gängigen Kassensystemen, Onlineshops und CRM-Lösungen.
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12, fontSize: "var(--fs-body)", color: "var(--fg-1)" }}>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> Kassenschnittstellen (POS)</li>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> Onlineshop-Integration</li>
                <li style={{ display: "flex", alignItems: "flex-start", gap: 8 }}><span style={{ color: "var(--ha-smart-mid)", fontWeight: 700 }}>✓</span> CRM & ERP Systeme</li>
              </ul>
              <div style={{ marginTop: "auto", paddingTop: 24 }}>
                <a href="https://www.helloagain.com/de/termin" style={{ color: "var(--ha-smart-mid)", textDecoration: "none", fontWeight: 700, fontSize: "var(--fs-body)", display: "flex", alignItems: "center", gap: 4 }}>
                  Termin vereinbaren <span aria-hidden="true">→</span>
                </a>
              </div>
            </div>
          </div>
        </div>
      </section>

      <footer className="legal-footer" style={{ background: "var(--ha-ink)", color: "rgba(255,255,255,0.7)", borderTop: "none", padding: "24px 0" }}>
        <div className="legal-inner">
          <span>© hello again GmbH</span>
          <span className="legal-links">
            <a href="https://www.helloagain.com/de/impressum" style={{ color: "rgba(255,255,255,0.7)", textDecoration: "none" }}>Impressum</a>
            <a href="https://www.helloagain.com/de/datenschutzerklaerung" style={{ color: "rgba(255,255,255,0.7)", textDecoration: "none" }}>Datenschutz</a>
          </span>
        </div>
      </footer>
    </React.Fragment>
  );
}

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