/* eslint-disable */
/**
 * Tech-Spec-Modal — globale React-Komponente window.TechSpecModal
 *
 * Zeigt eine vom AI generierte "Technische Aufgabe" mit 3D-Workflow-Infografik
 * und Pflicht-Akzeptanz-Checkbox vor der Bezahlung an.
 *
 * Props:
 *   open          — boolean, ob das Modal sichtbar ist
 *   quote         — Quote-Objekt aus dem Pricer
 *   customerIntent (optional) — Freitext-Kontext aus dem Chat
 *   onAccept(spec, specId) — wird aufgerufen, wenn Kunde akzeptiert
 *   onClose       — schließt das Modal
 *
 * Architektur:
 *   1. Beim ersten Render ruft die Komponente /api/generate-tech-spec auf
 *   2. Während des Ladens zeigt sie einen Lade-Indikator
 *   3. Bei Erfolg: Spec-Karte + three.js 3D-Workflow + Pflicht-Checkbox
 *   4. Nach Akzeptanz wird onAccept(spec, specId) aufgerufen
 */

(function (global) {
  const { useState, useEffect, useRef } = React;
  const t = window.t || function(de, en){ return de; };

  // ----- 3D Workflow Scene (three.js) -----
  function WorkflowScene3D({ steps, goal }) {
    const mountRef = useRef(null);
    const rafRef = useRef(0);

    useEffect(() => {
      if (!global.THREE || !mountRef.current) return;
      const T = global.THREE;
      const mount = mountRef.current;
      const w = mount.clientWidth || 600;
      const h = 280;

      const scene = new T.Scene();
      scene.background = null;
      scene.fog = new T.FogExp2(0x0a0e14, 0.045);

      const camera = new T.PerspectiveCamera(46, w / h, 0.1, 100);
      camera.position.set(0, 4.2, 11.5);
      camera.lookAt(0, 0, 0);

      const renderer = new T.WebGLRenderer({ antialias: true, alpha: true });
      renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
      renderer.setSize(w, h);
      renderer.setClearColor(0x000000, 0);
      mount.innerHTML = "";
      mount.appendChild(renderer.domElement);

      // ambient + directional + point lights
      scene.add(new T.AmbientLight(0xffffff, 0.45));
      const dir = new T.DirectionalLight(0xffd88a, 0.85);
      dir.position.set(6, 8, 6);
      scene.add(dir);
      const pt = new T.PointLight(0xffc760, 1.6, 18);
      pt.position.set(0, 2.5, 0);
      scene.add(pt);

      // group of step platforms
      const group = new T.Group();
      scene.add(group);

      const n = Math.max(3, Math.min(7, (steps && steps.length) || 5));
      const radius = 4.6;
      const platMeshes = [];
      const goldHex = 0xd9a441;
      const inkHex = 0xe6e1d5;

      for (let i = 0; i < n; i++) {
        const angle = (i / n) * Math.PI * 2 - Math.PI / 2;
        const x = Math.cos(angle) * radius;
        const z = Math.sin(angle) * radius;

        // Hexagonal platform
        const platGeo = new T.CylinderGeometry(0.95, 0.95, 0.22, 6);
        const platMat = new T.MeshStandardMaterial({
          color: i === 0 ? 0xf1d28d : goldHex,
          emissive: 0x2a1f00,
          emissiveIntensity: 0.55,
          metalness: 0.7,
          roughness: 0.32,
        });
        const plat = new T.Mesh(platGeo, platMat);
        plat.position.set(x, 0, z);
        plat.userData.baseY = 0;
        plat.userData.phase = i * 0.7;
        group.add(plat);
        platMeshes.push(plat);

        // Number marker (small sphere on top)
        const markerGeo = new T.SphereGeometry(0.18, 16, 16);
        const markerMat = new T.MeshStandardMaterial({
          color: inkHex,
          emissive: 0xfff0c8,
          emissiveIntensity: 0.6,
        });
        const marker = new T.Mesh(markerGeo, markerMat);
        marker.position.set(x, 0.4, z);
        group.add(marker);

        // Connection line to next platform
        if (i < n - 1) {
          const angleNext = ((i + 1) / n) * Math.PI * 2 - Math.PI / 2;
          const xNext = Math.cos(angleNext) * radius;
          const zNext = Math.sin(angleNext) * radius;
          const curvePts = [];
          for (let t = 0; t <= 1; t += 0.05) {
            const cx = x * (1 - t) + xNext * t;
            const cz = z * (1 - t) + zNext * t;
            const cy = 0.45 + Math.sin(t * Math.PI) * 0.7;
            curvePts.push(new T.Vector3(cx, cy, cz));
          }
          const curve = new T.CatmullRomCurve3(curvePts);
          const tubeGeo = new T.TubeGeometry(curve, 24, 0.04, 8, false);
          const tubeMat = new T.MeshStandardMaterial({
            color: goldHex,
            emissive: 0x4d3500,
            emissiveIntensity: 0.7,
            transparent: true,
            opacity: 0.85,
          });
          group.add(new T.Mesh(tubeGeo, tubeMat));
        }
      }

      // Center goal: glowing icosahedron
      const goalGeo = new T.IcosahedronGeometry(0.95, 1);
      const goalMat = new T.MeshStandardMaterial({
        color: 0xfff0c8,
        emissive: 0xffc760,
        emissiveIntensity: 1.5,
        metalness: 0.85,
        roughness: 0.2,
      });
      const goalMesh = new T.Mesh(goalGeo, goalMat);
      goalMesh.position.set(0, 1.5, 0);
      group.add(goalMesh);

      // Wireframe ring around goal
      const ringGeo = new T.TorusGeometry(1.6, 0.025, 12, 64);
      const ringMat = new T.MeshBasicMaterial({ color: goldHex, transparent: true, opacity: 0.55 });
      const ring = new T.Mesh(ringGeo, ringMat);
      ring.rotation.x = Math.PI / 2;
      ring.position.set(0, 1.5, 0);
      group.add(ring);

      // Subtle ground reflection plane
      const groundGeo = new T.CircleGeometry(7, 64);
      const groundMat = new T.MeshStandardMaterial({
        color: 0x0a0e14,
        metalness: 0.85,
        roughness: 0.55,
        transparent: true,
        opacity: 0.65,
      });
      const ground = new T.Mesh(groundGeo, groundMat);
      ground.rotation.x = -Math.PI / 2;
      ground.position.y = -0.5;
      scene.add(ground);

      let t = 0;
      const animate = () => {
        t += 0.012;
        group.rotation.y = t * 0.32;
        goalMesh.rotation.y = t * 1.3;
        goalMesh.rotation.x = t * 0.8;
        goalMesh.position.y = 1.5 + Math.sin(t * 1.6) * 0.18;
        ring.rotation.z = t * 0.6;
        platMeshes.forEach((p, i) => {
          p.position.y = p.userData.baseY + Math.sin(t * 1.4 + p.userData.phase) * 0.12;
        });
        renderer.render(scene, camera);
        rafRef.current = requestAnimationFrame(animate);
      };
      animate();

      // resize handler
      const onResize = () => {
        const newW = mount.clientWidth || w;
        camera.aspect = newW / h;
        camera.updateProjectionMatrix();
        renderer.setSize(newW, h);
      };
      window.addEventListener("resize", onResize);

      return () => {
        cancelAnimationFrame(rafRef.current);
        window.removeEventListener("resize", onResize);
        renderer.dispose();
        if (mount && renderer.domElement && renderer.domElement.parentNode === mount) {
          mount.removeChild(renderer.domElement);
        }
      };
    }, [steps && steps.length]);

    return React.createElement("div", {
      ref: mountRef,
      style: {
        width: "100%",
        height: 280,
        borderRadius: 12,
        background: "linear-gradient(180deg, rgba(217,164,65,0.06) 0%, rgba(10,14,20,0.4) 100%)",
        border: "1px solid var(--line, #2a2620)",
        overflow: "hidden",
        marginTop: 12,
      },
    });
  }

  // ----- Main Modal -----
  function TechSpecModal({ open, quote, customerIntent, chatHistory, onAccept, onClose }) {
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [spec, setSpec] = useState(null);
    const [specId, setSpecId] = useState(null);
    const [accepted, setAccepted] = useState(false);

    useEffect(() => {
      if (!open || !quote) return;
      setLoading(true);
      setError(null);
      setSpec(null);
      setAccepted(false);

      fetch("/api/generate-tech-spec", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ quote, customerIntent: customerIntent || "", lang: window.__lang || "de" }),
      })
        .then((r) => r.json())
        .then((data) => {
          if (data && data.spec) {
            setSpec(data.spec);
            setSpecId(data.specId);
          } else {
            setError(data && data.error ? data.error : t("Unbekannter Fehler bei Spec-Generierung.", "Unknown error during spec generation."));
          }
          setLoading(false);
        })
        .catch((e) => {
          setError(t("Netzwerk-Fehler: ", "Network error: ") + (e && e.message ? e.message : t("unbekannt", "unknown")));
          setLoading(false);
        });
    }, [open, quote && (quote.problem + "" + quote.finalPrice)]);

    if (!open) return null;

    const acceptStyle = accepted
      ? { opacity: 1, cursor: "pointer" }
      : { opacity: 0.4, cursor: "not-allowed" };

    return React.createElement(
      "div",
      { className: "modal-bg", onClick: onClose },
      React.createElement(
        "div",
        {
          className: "modal",
          onClick: (e) => e.stopPropagation(),
          style: { position: "relative", maxWidth: 760, maxHeight: "92vh", overflowY: "auto" },
        },
        React.createElement("button", { className: "modal-close", onClick: onClose }, "×"),
        React.createElement(
          "div",
          {
            className: "eyebrow",
            style: { marginBottom: 10 },
          },
          t("Schritt 1 von 3 · Technische Aufgabe", "Step 1 of 3 · Technical Specification")
        ),
        React.createElement("h3", null, t("Verbindlicher Leistungsumfang.", "Binding scope of work.")),
        React.createElement(
          "p",
          { style: { color: "var(--ink-dim)", fontSize: 14, marginTop: 8 } },
          t("Bevor Sie zahlen, sehen Sie hier die KI-generierte ", "Before you pay, here is the AI-generated "),
          React.createElement("b", null, t("Technische Aufgabe", "Technical Specification")),
          t(" — exakt, was geliefert wird, was NICHT enthalten ist und welche Anpassungen im Festpreis abgedeckt sind. Diese Aufgabe wird Bestandteil der Bestellung.", " — exactly what will be delivered, what is NOT included, and which adjustments are covered by the fixed price. This specification becomes part of the order.")
        ),
        loading &&
          React.createElement(
            "div",
            {
              style: {
                padding: "40px 20px",
                textAlign: "center",
                color: "var(--ink-dim)",
                fontSize: 14,
              },
            },
            React.createElement(
              "div",
              { style: { fontSize: 32, marginBottom: 12, opacity: 0.6 } },
              "⚙️"
            ),
            t("Technische Aufgabe wird erzeugt…", "Generating technical specification…"),
            React.createElement(
              "div",
              { style: { fontSize: 12, marginTop: 6, color: "var(--ink-mute)" } },
              t("Claude analysiert Ihr Anliegen und strukturiert die Liefer-Schritte.", "Claude is analysing your request and structuring the delivery steps.")
            )
          ),
        error &&
          React.createElement(
            "div",
            {
              style: {
                padding: "20px",
                margin: "16px 0",
                borderRadius: 10,
                background: "rgba(220,80,80,0.08)",
                border: "1px solid rgba(220,80,80,0.4)",
                color: "var(--ink)",
              },
            },
            React.createElement(
              "b",
              { style: { color: "#ff8888" } },
              t("Spec-Generierung fehlgeschlagen.", "Spec generation failed.")
            ),
            React.createElement("br"),
            React.createElement(
              "span",
              { style: { fontSize: 13, color: "var(--ink-dim)" } },
              String(error).slice(0, 300)
            ),
            React.createElement("br"),
            React.createElement(
              "button",
              {
                className: "btn btn-ghost",
                style: { marginTop: 12 },
                onClick: onClose,
              },
              t("Schliessen — bitte später erneut versuchen", "Close — please try again later")
            )
          ),
        spec &&
          React.createElement(
            "div",
            { style: { marginTop: 16 } },
            // Title + Goal
            React.createElement(
              "div",
              {
                style: {
                  padding: "14px 16px",
                  borderRadius: 10,
                  background: "var(--bg-elev, #14110c)",
                  border: "1px solid var(--gold, #d9a441)",
                },
              },
              React.createElement(
                "div",
                {
                  style: {
                    fontFamily: "var(--mono)",
                    fontSize: 10,
                    letterSpacing: "0.16em",
                    color: "var(--gold, #d9a441)",
                    marginBottom: 6,
                    textTransform: "uppercase",
                  },
                },
                t("Projektziel", "Project goal")
              ),
              React.createElement(
                "div",
                { style: { color: "var(--ink)", fontSize: 18, fontWeight: 600, marginBottom: 6 } },
                spec.title
              ),
              React.createElement(
                "div",
                { style: { color: "var(--ink-dim)", fontSize: 14, lineHeight: 1.5 } },
                spec.goal
              )
            ),
            // 3D Infografik
            React.createElement(WorkflowScene3D, { steps: spec.steps, goal: spec.goal }),
            // Steps list
            React.createElement(
              "div",
              { style: { marginTop: 18 } },
              React.createElement(
                "div",
                {
                  style: {
                    fontFamily: "var(--mono)",
                    fontSize: 10,
                    letterSpacing: "0.16em",
                    color: "var(--gold)",
                    marginBottom: 10,
                    textTransform: "uppercase",
                  },
                },
                t("Schritte (chronologisch)", "Steps (chronological)")
              ),
              spec.steps.map((s, i) =>
                React.createElement(
                  "div",
                  {
                    key: i,
                    style: {
                      display: "grid",
                      gridTemplateColumns: "36px 1fr auto",
                      gap: 12,
                      padding: "10px 0",
                      borderBottom: i < spec.steps.length - 1 ? "1px solid var(--line, #2a2620)" : "none",
                    },
                  },
                  React.createElement(
                    "div",
                    {
                      style: {
                        width: 28,
                        height: 28,
                        borderRadius: "50%",
                        background: "var(--gold, #d9a441)",
                        color: "#1a1408",
                        fontWeight: 700,
                        fontSize: 13,
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                      },
                    },
                    String(i + 1)
                  ),
                  React.createElement(
                    "div",
                    null,
                    React.createElement(
                      "div",
                      { style: { color: "var(--ink)", fontWeight: 600, fontSize: 14, marginBottom: 3 } },
                      s.title
                    ),
                    React.createElement(
                      "div",
                      { style: { color: "var(--ink-dim)", fontSize: 13, lineHeight: 1.5 } },
                      s.detail
                    )
                  ),
                  React.createElement(
                    "div",
                    {
                      style: {
                        fontFamily: "var(--mono)",
                        fontSize: 11,
                        color: "var(--gold)",
                        whiteSpace: "nowrap",
                        paddingTop: 4,
                      },
                    },
                    s.duration || ""
                  )
                )
              )
            ),
            // Two-col: deliverables + notIncluded
            React.createElement(
              "div",
              {
                style: {
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 14,
                  marginTop: 20,
                },
              },
              React.createElement(
                "div",
                {
                  style: {
                    padding: "12px 14px",
                    borderRadius: 10,
                    background: "rgba(217,164,65,0.06)",
                    border: "1px solid rgba(217,164,65,0.25)",
                  },
                },
                React.createElement(
                  "div",
                  {
                    style: {
                      fontFamily: "var(--mono)",
                      fontSize: 10,
                      letterSpacing: "0.14em",
                      color: "var(--gold)",
                      marginBottom: 8,
                      textTransform: "uppercase",
                    },
                  },
                  t("✓ Im Festpreis enthalten", "✓ Included in fixed price")
                ),
                React.createElement(
                  "ul",
                  { style: { margin: 0, paddingLeft: 18, fontSize: 13, color: "var(--ink-dim)", lineHeight: 1.55 } },
                  (spec.deliverables || []).map((d, i) =>
                    React.createElement("li", { key: i, style: { marginBottom: 4 } }, d)
                  )
                )
              ),
              React.createElement(
                "div",
                {
                  style: {
                    padding: "12px 14px",
                    borderRadius: 10,
                    background: "rgba(220,80,80,0.05)",
                    border: "1px solid rgba(220,80,80,0.25)",
                  },
                },
                React.createElement(
                  "div",
                  {
                    style: {
                      fontFamily: "var(--mono)",
                      fontSize: 10,
                      letterSpacing: "0.14em",
                      color: "#ff9999",
                      marginBottom: 8,
                      textTransform: "uppercase",
                    },
                  },
                  t("✗ NICHT enthalten", "✗ NOT included")
                ),
                React.createElement(
                  "ul",
                  { style: { margin: 0, paddingLeft: 18, fontSize: 13, color: "var(--ink-dim)", lineHeight: 1.55 } },
                  (spec.notIncluded || []).map((d, i) =>
                    React.createElement("li", { key: i, style: { marginBottom: 4 } }, d)
                  )
                )
              )
            ),
            // Revision policy + Timeline
            React.createElement(
              "div",
              {
                style: {
                  marginTop: 16,
                  padding: "12px 14px",
                  borderRadius: 10,
                  background: "var(--bg-elev, #14110c)",
                  border: "1px solid var(--line-strong, #3a3528)",
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 14,
                  fontSize: 13,
                  color: "var(--ink-dim)",
                  lineHeight: 1.5,
                },
              },
              React.createElement(
                "div",
                null,
                React.createElement(
                  "div",
                  { style: { color: "var(--gold)", fontSize: 11, marginBottom: 4, fontFamily: "var(--mono)", letterSpacing: "0.1em", textTransform: "uppercase" } },
                  "Timeline"
                ),
                spec.timeline
              ),
              React.createElement(
                "div",
                null,
                React.createElement(
                  "div",
                  { style: { color: "var(--gold)", fontSize: 11, marginBottom: 4, fontFamily: "var(--mono)", letterSpacing: "0.1em", textTransform: "uppercase" } },
                  t("Abnahme", "Acceptance")
                ),
                spec.acceptanceCriteria
              )
            ),
            // Revisions policy callout
            React.createElement(
              "div",
              {
                style: {
                  marginTop: 14,
                  padding: "12px 14px",
                  borderRadius: 10,
                  background: "rgba(217,164,65,0.08)",
                  border: "1px solid var(--gold)",
                  fontSize: 13,
                  color: "var(--ink)",
                  lineHeight: 1.5,
                },
              },
              React.createElement(
                "div",
                { style: { color: "var(--gold)", fontSize: 11, marginBottom: 6, fontFamily: "var(--mono)", letterSpacing: "0.1em", textTransform: "uppercase" } },
                t("Revisions-Klausel — verbindlich", "Revision clause — binding")
              ),
              spec.revisionPolicy
            ),
            // Acceptance checkbox
            React.createElement(
              "label",
              {
                style: {
                  display: "flex",
                  alignItems: "flex-start",
                  gap: 10,
                  marginTop: 22,
                  padding: "14px 16px",
                  borderRadius: 10,
                  border: accepted ? "1px solid var(--gold)" : "1px solid var(--line-strong, #3a3528)",
                  background: accepted ? "rgba(217,164,65,0.06)" : "transparent",
                  cursor: "pointer",
                  fontSize: 14,
                  color: "var(--ink)",
                  lineHeight: 1.5,
                  transition: "border-color .15s, background .15s",
                },
              },
              React.createElement("input", {
                type: "checkbox",
                checked: accepted,
                onChange: (e) => setAccepted(e.target.checked),
                style: { marginTop: 3, accentColor: "var(--gold)", cursor: "pointer", flex: "0 0 auto" },
              }),
              React.createElement(
                "span",
                null,
                React.createElement("b", null, t("Ich akzeptiere die Technische Aufgabe als verbindlichen Bestellumfang.", "I accept the Technical Specification as the binding scope of the order.")),
                t(" Mir ist bewusst, dass die oben genannten Schritte und Deliverables den vollständigen Liefer-Umfang definieren. Anpassungen außerhalb der Revisions-Klausel (max. 2 kleine Änderungen) erfordern eine neue Bestellung.", " I am aware that the steps and deliverables listed above define the full scope of delivery. Adjustments outside the revision clause (max. 2 small changes) require a new order.")
              )
            ),
            // Action buttons
            React.createElement(
              "div",
              { style: { display: "flex", gap: 10, marginTop: 20 } },
              React.createElement(
                "button",
                { className: "btn btn-ghost", onClick: onClose, style: { flex: 0 } },
                t("Abbrechen", "Cancel")
              ),
              React.createElement(
                "button",
                {
                  className: "btn btn-primary btn-arrow",
                  style: Object.assign({ flex: 1 }, acceptStyle),
                  disabled: !accepted,
                  onClick: () => {
                    if (!accepted) return;
                    // Fire-and-forget: an Maksym mailen + in Vectorize speichern
                    try {
                      const chatPayload = Array.isArray(chatHistory) && chatHistory.length
                        ? chatHistory
                        : (customerIntent ? [{ role: "user", content: String(customerIntent) }] : []);
                      fetch("/api/log-customer-event", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({
                          type: "tech_spec_accepted",
                          payload: { spec, specId, quote },
                          chatHistory: chatPayload,
                        }),
                        keepalive: true,
                      }).catch(() => {});
                    } catch (e) { /* never block accept */ }
                    onAccept && onAccept(spec, specId);
                  },
                },
                t("Weiter zur Bezahlmethode →", "Continue to payment →")
              )
            )
          )
      )
    );
  }

  global.TechSpecModal = TechSpecModal;
})(window);
