/* global React, useReveal, Topo, ArrowRight */
const { useState, useEffect, useRef } = React;

/* ---------- Positioning / Manifesto ---------- */

function Positioning() {
  const ref = useReveal();
  return (
    <section className="section manifesto" id="positionierung">
      <div className="wrap reveal" ref={ref}>
        <div className="section-head">
          <div className="label-col">
            <span className="num">N° 01</span>
            <span className="name">Haltung</span>
          </div>
          <span className="eyebrow">Was wir glauben</span>
        </div>

        <div className="manifesto-grid">
          <blockquote>
            Die meisten KI-Projekte scheitern nicht an der Technik.
            Sie scheitern, weil niemand <span className="em">vorher</span> den Prozess
            sauber gelesen hat. Und niemand danach die Adoption begleitet.
          </blockquote>

          <div className="manifesto-aside">
            <div className="fact">
              <span className="n">01</span>
              <span className="t">Wir starten beim Prozess, nicht beim Modell. Erst wenn die Arbeit klar ist, entscheiden wir, wo KI tatsächlich Nutzen bringt.</span>
            </div>
            <div className="fact">
              <span className="n">02</span>
              <span className="t">Wir sagen ab, wenn KI nicht das richtige Werkzeug ist. Manchmal ist die ehrliche Antwort eine bessere Vorlage oder ein klarer Workflow.</span>
            </div>
            <div className="fact">
              <span className="n">03</span>
              <span className="t">Wir messen in Geschäftsergebnis, nicht in Token. Erfolg ist ein Prozess, den Ihr Team tatsächlich verwendet.</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Method Stepper (the Höhenlinien) ---------- */

function MountainScene({ active }) {
  // Camp X-positions roughly align with the 3 step columns below (1/6, 3/6, 5/6 of viewBox).
  // Y-positions sit on the foreground ridge silhouette.
  const camps = [
    {
      x: 200, y: 378, n: '01',
      titleA: 'Prozesse lesen,',
      titleB: 'wie sie wirklich laufen.'
    },
    {
      x: 600, y: 220, n: '02',
      titleA: 'Mit dem höchsten',
      titleB: 'ROI starten.'
    },
    {
      x: 1000, y: 92, n: '03',
      titleA: 'Verankern, schulen,',
      titleB: 'übergeben.'
    }
  ];

  // The path the climber follows. Shared by underlay (planned) and overlay (completed).
  // Switchback trail — alpine hiker pattern, not a smooth curve.
  const routeD =
    "M 200 378 " +
    "L 280 360 L 240 342 L 340 326 L 290 308 L 400 292 L 350 274 L 470 258 L 420 242 L 540 232 L 510 224 L 600 220 " +
    "L 680 208 L 640 192 L 740 175 L 700 158 L 820 142 L 780 122 L 880 108 L 850 100 L 940 95 L 970 92 L 1000 92";

  // Progress 0..1 — how far the solid overlay reaches.
  const progress = (active + 1) / 3;
  const climber = camps[active];

  return (
    <svg
      viewBox="0 0 1200 440"
      className="mountain-svg"
      preserveAspectRatio="xMidYMid meet"
      aria-hidden="true"
    >
      <defs>
        <linearGradient id="ridge-near" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="var(--primary)" stopOpacity="0.18" />
          <stop offset="1" stopColor="var(--primary)" stopOpacity="0.05" />
        </linearGradient>
        <linearGradient id="ridge-mid" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="var(--primary)" stopOpacity="0.10" />
          <stop offset="1" stopColor="var(--primary)" stopOpacity="0.02" />
        </linearGradient>
        <linearGradient id="ridge-far" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="var(--primary)" stopOpacity="0.06" />
          <stop offset="1" stopColor="var(--primary)" stopOpacity="0.01" />
        </linearGradient>
      </defs>

      {/* Drifting cloud bands (very subtle) */}
      <g className="clouds" aria-hidden="true">
        <ellipse cx="180" cy="120" rx="120" ry="6" fill="var(--paper)" opacity="0.55" />
        <ellipse cx="820" cy="60"  rx="160" ry="5" fill="var(--paper)" opacity="0.50" />
      </g>

      {/* Far ridge — distant jagged peaks */}
      <path
        d="M 0 440 L 0 295 L 90 280 L 170 290 L 260 250 L 340 270 L 430 230 L 510 245 L 590 200 L 670 215 L 760 165 L 840 180 L 930 130 L 1010 145 L 1100 95 L 1200 80 L 1200 440 Z"
        fill="url(#ridge-far)"
        stroke="var(--primary)"
        strokeWidth="0.5"
        strokeOpacity="0.18"
        strokeLinejoin="round"
      />

      {/* Mid ridge — sharper alpine peaks */}
      <path
        d="M 0 440 L 0 345 L 60 360 L 130 320 L 200 340 L 280 270 L 360 295 L 450 230 L 520 255 L 600 175 L 680 200 L 770 130 L 850 155 L 940 88 L 1020 110 L 1110 65 L 1200 78 L 1200 440 Z"
        fill="url(#ridge-mid)"
        stroke="var(--primary)"
        strokeWidth="0.7"
        strokeOpacity="0.26"
        strokeLinejoin="round"
      />

      {/* Foreground ridge — full jagged silhouette, summits coincide with camps */}
      <path
        d="M 0 440
           L 0 398 L 50 410 L 110 380 L 170 395 L 200 360
           L 230 388 L 280 372 L 330 340 L 380 365 L 430 310
           L 480 335 L 530 280 L 575 245 L 600 220
           L 640 244 L 690 210 L 730 178 L 780 200 L 830 160
           L 870 178 L 910 140 L 950 120 L 985 100 L 1000 92
           L 1050 110 L 1100 90 L 1150 80 L 1200 75
           L 1200 440 Z"
        fill="url(#ridge-near)"
        stroke="var(--primary)"
        strokeWidth="0.9"
        strokeOpacity="0.55"
        strokeLinejoin="round"
      />

      {/* Snow caps — multiple peaks on the upper half of the foreground ridge */}
      <path
        d="M 530 280 L 575 245 L 600 220 L 640 244"
        fill="none"
        stroke="var(--paper)"
        strokeWidth="2.4"
        strokeOpacity="0.55"
        strokeLinejoin="round"
        strokeLinecap="round"
      />
      <path
        d="M 690 210 L 730 178 L 780 200"
        fill="none"
        stroke="var(--paper)"
        strokeWidth="2.6"
        strokeOpacity="0.65"
        strokeLinejoin="round"
        strokeLinecap="round"
      />
      <path
        d="M 830 160 L 870 178 L 910 140 L 950 120 L 985 100 L 1000 92 L 1050 110 L 1100 90 L 1150 80 L 1200 75"
        fill="none"
        stroke="var(--paper)"
        strokeWidth="3.2"
        strokeOpacity="0.82"
        strokeLinejoin="round"
        strokeLinecap="round"
      />

      {/* (Treeline removed per design feedback — kept the scene clean.) */}

      {/* Planned route — faint, dashed */}
      <path
        d={routeD}
        fill="none"
        stroke="var(--accent)"
        strokeWidth="1.2"
        strokeDasharray="3 5"
        strokeOpacity="0.35"
        strokeLinecap="round"
      />

      {/* Completed route — drawn progressively from start to current camp */}
      <path
        d={routeD}
        fill="none"
        stroke="var(--accent)"
        strokeWidth="2.2"
        strokeLinecap="round"
        pathLength="1"
        className="route-completed"
        style={{
          strokeDasharray: 1,
          strokeDashoffset: 1 - progress,
          transition: 'stroke-dashoffset 900ms cubic-bezier(0.65, 0.05, 0.35, 1)'
        }}
      />

      {/* Column markers — short vertical ticks at the bottom of the SVG, one per camp.
          These visually bridge each summit to its step card directly below. */}
      {camps.map((c, i) => (
        <line
          key={`mark-${i}`}
          x1={c.x} y1={418}
          x2={c.x} y2={440}
          className={`column-mark ${i === active ? 'active' : ''}`}
        />
      ))}

      {/* Camps */}
      {camps.map((c, i) => (
        <g
          key={i}
          transform={`translate(${c.x}, ${c.y})`}
          className={`scene-camp ${i <= active ? 'reached' : ''} ${i === active ? 'current' : ''}`}
        >
          <line x1="0" y1="0" x2="0" y2="-26" className="camp-pole" />
          <path d="M 0 -26 L 16 -21 L 0 -16 Z" className="camp-flag" />
          <circle cx="0" cy="0" r="3.5" className="camp-dot" />
          <text textAnchor="middle" className="camp-num">
            <tspan x="0" y="24">{c.n}</tspan>
          </text>
          <text textAnchor="middle" className="camp-title">
            <tspan x="0" y="42">{c.titleA}</tspan>
            <tspan x="0" y="58">{c.titleB}</tspan>
          </text>
        </g>
      ))}

      {/* Climber marker (halo + dot) — rests exactly on the active camp's base point */}
      <g
        className="climber"
        style={{
          transform: `translate(${climber.x}px, ${climber.y}px)`,
          transition: 'transform 900ms cubic-bezier(0.65, 0.05, 0.35, 1)'
        }}
      >
        <circle r="13" className="climber-halo" />
        <circle r="5"  className="climber-core" />
      </g>
    </svg>
  );
}

function Methodik() {
  const ref = useReveal();
  const [active, setActive] = useState(0);
  const [inView, setInView] = useState(false);
  const userTouchedRef = useRef(false);
  const sectionRef = useRef(null);

  // Detect when section enters viewport, then trigger the autoplay.
  useEffect(() => {
    if (!sectionRef.current) return;
    const io = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) { setInView(true); io.disconnect(); }
      },
      { threshold: 0.1 }
    );
    io.observe(sectionRef.current);
    return () => io.disconnect();
  }, []);

  // Autoplay 0 → 1 → 2 once when section is visible; cancel if user hovers.
  useEffect(() => {
    if (!inView || userTouchedRef.current) return;
    const t1 = setTimeout(() => { if (!userTouchedRef.current) setActive(1); }, 1500);
    const t2 = setTimeout(() => { if (!userTouchedRef.current) setActive(2); }, 3000);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [inView]);

  const focusStep = (i) => {
    userTouchedRef.current = true;
    setActive(i);
  };

  const steps = [
    {
      stage: "Stufe 01",
      alt: "DIAGNOSE",
      title: "Prozesse lesen, wie sie wirklich laufen.",
      desc: "Experten-Interviews, vor Ort beim Team, über die Schulter schauen. Wir verstehen Ihre Abläufe so, wie sie im Alltag passieren, nicht wie sie im Org-Chart stehen.",
      output: "Impact-Effort-Matrix",
      outputDesc: "Use Cases nach Aufwand und Wirkung priorisiert. Klares Bild, womit zuerst gestartet wird."
    },
    {
      stage: "Stufe 02",
      alt: "ERSTE WINS",
      title: "Mit dem höchsten ROI starten.",
      desc: "Wir beginnen mit den Use Cases, die spürbar wirken. Aus eigener Erfahrung: kleine, sichtbare Erfolge bauen Vertrauen auf. Die Menschen, die später damit arbeiten, müssen die Lösung mittragen.",
      output: "Pilot im Einsatz",
      outputDesc: "Erste laufende Lösung, vom Team getestet und mit messbarer Wirkung."
    },
    {
      stage: "Stufe 03",
      alt: "INTEGRATION",
      title: "Verankern, schulen, übergeben.",
      desc: "Enge Begleitung, kontinuierliches Feedback, gemeinsame Anpassung. Nach erfolgreichem Test integrieren wir die Prozesse in den Alltag und schulen die Anwender, bis das Team eigenständig weiterarbeiten kann.",
      output: "Change Management",
      outputDesc: "Schulung, Adoption und Übergabe. Das Team arbeitet ohne uns weiter, Ownership bleibt im Haus."
    }
  ];

  return (
    <section className="section" id="methodik" ref={sectionRef}>
      <Topo seed={3} opacity={0.35} lines={7} />
      <div className="wrap reveal" ref={ref}>
        <div className="section-head">
          <div className="label-col">
            <span className="num">N° 02</span>
            <span className="name">Methodik</span>
          </div>
          <div>
            <span className="eyebrow">Drei Höhenstufen</span>
            <h2 className="h-1" style={{ marginTop: 16, maxWidth: '20ch' }}>
              Wie ein Projekt mit uns abläuft.
            </h2>
          </div>
        </div>

        <div className="method-scene">
          <MountainScene active={active} />
        </div>

        <div className="method-stepper">
          {steps.map((s, i) => (
            <div
              key={i}
              className={`step ${active === i ? 'active' : ''}`}
              onMouseEnter={() => focusStep(i)}
              onFocus={() => focusStep(i)}
              tabIndex={0}
            >
              <div className="step-header">
                <span className="stage">{s.stage}</span>
                <span className="alt">{s.alt}</span>
              </div>
              <h3>{s.title}</h3>
              <p>{s.desc}</p>
              <div className="step-output">
                <span className="step-output-label">Ergebnis</span>
                <strong className="step-output-name">{s.output}</strong>
                <span className="step-output-desc">{s.outputDesc}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Services ribbon ---------- */

function Leistungen() {
  const [open, setOpen] = useState(null);
  const services = [
    {
      title: "KI-Strategie",
      sub: "Diagnose · Roadmap · Business Case",
      desc: "Wir lesen Ihre Organisation als System: wo entstehen Engpässe, wo gibt es echte Daten, wo lohnt sich KI wirklich. Ergebnis ist eine priorisierte Roadmap, mit der Sie intern Zustimmung holen können.",
      output: ["KI-Landkarte des Unternehmens", "Priorisierte Use-Case-Liste", "Roadmap mit klaren Quartalsschritten", "Business Case je Use Case"]
    },
    {
      title: "Workshops",
      sub: "Führungskräfte · Teams · Geschäftsleitung",
      desc: "Keine Tool-Demos. Wir arbeiten an konkreten Workflows aus Ihrem Tagesgeschäft. Am Ende des Tages haben Teilnehmende mindestens drei eigene Use Cases identifiziert und einen davon prototypisch gelöst.",
      output: ["Impulsformat für Führung", "Vertiefungs-Workshop pro Team", "Mehrteilige Programme fürs ganze Haus", "Workshop-Dokumentation"]
    },
    {
      title: "Automatisierung",
      sub: "Workflows · Integration · Operations",
      desc: "Wir verbinden Ihre Systeme (CRM, ERP, Dokumente, Mail) mit KI dort, wo sie messbar Zeit spart. Konkret, getestet, mit Hand-off-Doku für Ihr Team oder IT.",
      output: ["Workflow-Audit", "Implementation Sprint", "Monitoring & Übergabe", "Schulung für Anwender"]
    },
    {
      title: "Individuelle KI-Lösungen",
      sub: "Prototyp · Custom System · Produkt",
      desc: "Wenn Standard nicht reicht: wir bauen mit ausgewähltem Netzwerk maßgeschneiderte KI-Systeme: von Entscheidungs-Assistenten über Dokument-Pipelines bis zu kundenfertigen Produkten.",
      output: ["Discovery & Architektur", "Prototyp", "MVP-Entwicklung", "Begleiteter Rollout"]
    }
  ];

  return (
    <section className="section services" id="leistungen">
      <div className="wrap">
        <div className="section-head">
          <div className="label-col">
            <span className="num" style={{ color: '#fff', opacity: 0.7 }}>N° 03</span>
            <span className="name">Leistungen</span>
          </div>
          <div>
            <span className="eyebrow">Vier Wege zur Zusammenarbeit</span>
            <h2 className="h-1" style={{ marginTop: 16, maxWidth: '22ch', color: 'var(--bg)' }}>
              Manche brauchen einen Workshop. Andere ein ganzes System.
            </h2>
          </div>
        </div>

        <div className="service-list">
          {services.map((s, i) => (
            <React.Fragment key={i}>
              <div
                className={`service-row ${open === i ? 'open-state' : ''}`}
                onClick={() => setOpen(open === i ? null : i)}
              >
                <span className="sn">0{i + 1}</span>
                <div>
                  <div className="st">{s.title}</div>
                  <div className="stsub">{s.sub}</div>
                </div>
                <button className="open" aria-label="Details">
                  <svg viewBox="0 0 14 14" fill="none">
                    <path d="M7 1v12M1 7h12" stroke="currentColor" strokeWidth="1.2" />
                  </svg>
                </button>
              </div>
              {open === i && (
                <div className="service-detail">
                  <span></span>
                  <div>
                    <h4>Worum es geht</h4>
                    <p>{s.desc}</p>
                  </div>
                  <div>
                    <h4>Was Sie bekommen</h4>
                    <ul>{s.output.map((o, j) => <li key={j}>{o}</li>)}</ul>
                  </div>
                  <div>
                    <h4>Nächster Schritt</h4>
                    <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.75)', marginTop: 0 }}>
                      Umfang, Dauer und Investment besprechen wir individuell, abgestimmt auf Ihren Kontext.
                    </p>
                    <a href="#kontakt" className="link" style={{ marginTop: 18, color: 'var(--bg)', borderColor: 'rgba(255,255,255,0.4)' }}>
                      Anfragen
                    </a>
                  </div>
                </div>
              )}
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Positioning, Methodik, Leistungen });
