<!-- ============================================================
  Kantteile-Konfigurator – Trapezblechverkauf24
  Einbau: In WordPress im Block "Eigenes HTML" einfügen.
  Preis & Grenzwerte: Abschnitt CONFIG im Script ganz unten anpassen.
============================================================ -->
<style>
.tb24 { --ink:#0f172a; --muted:#64748b; --line:#e2e8f0; --bg:#f8fafc; --accent:#ea580c; --accent-d:#c2410c; --focus:#2563eb;
  max-width:980px; margin:24px auto; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
  color:var(--ink); background:#fff; border:1px solid var(--line); border-radius:8px; overflow:hidden;
  box-shadow:0 10px 15px -3px rgba(0,0,0,.08); line-height:1.4; }
.tb24 *, .tb24 *::before, .tb24 *::after { box-sizing:border-box; }
.tb24 h2, .tb24 h3 { margin:0; padding:0; font-weight:700; }
.tb24-head { background:#1e293b; color:#fff; padding:22px 24px; text-align:center; }
.tb24-head h2 { font-size:clamp(20px,3.4vw,26px); color:#fff; }
.tb24-head p { margin:6px 0 0; color:#cbd5e1; font-size:15px; }
.tb24-body { display:flex; flex-wrap:wrap; }
.tb24-side { flex:1 1 320px; padding:22px; background:var(--bg); border-right:1px solid var(--line); }
.tb24-main { flex:2 1 440px; padding:22px; display:flex; flex-direction:column; min-width:0; }
.tb24-group { margin-bottom:14px; }
.tb24-group label { display:block; font-weight:600; font-size:14px; margin-bottom:5px; color:#334155; }
.tb24 input, .tb24 select { width:100%; height:44px; padding:0 12px; border:1px solid #cbd5e1; border-radius:6px; font-size:16px; background:#fff; color:var(--ink); margin:0; }
.tb24 input:focus-visible, .tb24 select:focus-visible, .tb24-btn:focus-visible, .tb24-tab:focus-visible { outline:3px solid var(--focus); outline-offset:1px; }
.tb24 input.is-bad { border-color:#dc2626; background:#fef2f2; }
.tb24-row { display:flex; gap:12px; } .tb24-row > .tb24-group { flex:1; }
.tb24-dim { background:#fff; border:1px solid var(--line); border-radius:6px; padding:14px; margin-bottom:16px; }
.tb24-dim h3 { font-size:15px; margin-bottom:10px; }
.tb24-desc { font-size:13px; color:var(--muted); margin:0 0 14px; }
.tb24-swatches { display:flex; flex-wrap:wrap; gap:14px; }
.tb24-swatch { position:relative; display:flex !important; align-items:center; gap:8px; margin:0 !important; font-weight:500 !important; cursor:pointer; }
.tb24-swatch input { position:absolute; opacity:0; width:100%; height:100%; margin:0; cursor:pointer; left:0; top:0; }
.tb24-swatch span { display:block; width:36px; height:36px; flex:none; border-radius:50%; border:2px solid #fff; box-shadow:0 0 0 1px #94a3b8; }
.tb24-swatch input:checked + span { box-shadow:0 0 0 3px var(--ink); }
.tb24-swatch input:focus-visible + span { box-shadow:0 0 0 3px var(--focus); }

/* Vorschau */
.tb24-top { display:flex; flex-wrap:wrap; gap:10px; justify-content:space-between; align-items:center; }
.tb24-tabs { display:inline-flex; background:#e2e8f0; border-radius:8px; padding:3px; }
.tb24-tab { border:0; background:transparent; padding:0 14px; height:34px; border-radius:6px; font-size:14px; font-weight:600; color:#475569; cursor:pointer; }
.tb24-tab[aria-pressed="true"] { background:#fff; color:var(--ink); box-shadow:0 1px 3px rgba(15,23,42,.18); }
.tb24-canvas { margin:12px 0; border:1px solid var(--line); border-radius:8px; overflow:hidden;
  background-color:#f8fafc;
  background-image:linear-gradient(rgba(148,163,184,.22) 1px,transparent 1px),linear-gradient(90deg,rgba(148,163,184,.22) 1px,transparent 1px);
  background-size:24px 24px; }
.tb24-canvas svg { display:block; width:100%; height:auto; aspect-ratio:3/2; }
.tb24-legend { display:flex; flex-wrap:wrap; gap:6px 18px; font-size:13px; color:var(--muted); margin-bottom:12px; }
.tb24-legend i { display:inline-block; width:22px; height:6px; border-radius:3px; margin-right:6px; vertical-align:middle; }
.tb24-facts { display:flex; flex-wrap:wrap; gap:6px 24px; font-size:14px; color:#475569; }
.tb24-warn { margin-top:12px; padding:10px 14px; background:#fef2f2; border:1px solid #fecaca; color:#991b1b; border-radius:6px; font-size:14px; }
.tb24-warn ul { margin:0; padding-left:18px; }
.tb24-foot { display:flex; flex-wrap:wrap; gap:16px; justify-content:space-between; align-items:center; padding:20px 22px; border-top:1px solid var(--line); background:#fff; }
.tb24-price { font-size:32px; font-weight:800; line-height:1.1; }
.tb24-sub { font-size:13px; color:var(--muted); }
.tb24-actions { display:flex; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
.tb24-btn { background:var(--accent); color:#fff; border:0; padding:0 28px; height:48px; font-size:16px; font-weight:700; border-radius:6px; cursor:pointer; }
.tb24-btn:hover:not(:disabled) { background:var(--accent-d); }
.tb24-btn:disabled { background:#cbd5e1; cursor:not-allowed; }
.tb24-btn.alt { background:#334155; }
.tb24-btn.alt:hover:not(:disabled) { background:#1e293b; }
.tb24-status { display:none; margin:0; padding:10px 22px; border-top:1px solid var(--line); font-size:14px; }
.tb24-status.ok { display:block; background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
.tb24-status.err { display:block; background:#fef2f2; color:#991b1b; border-color:#fecaca; }
.tb24-summary { display:none; margin:0; padding:16px 22px; background:#f0fdf4; border-top:1px solid #bbf7d0; font-size:14px; white-space:pre-wrap; font-family:inherit; }
@media (max-width:640px){ .tb24-side{border-right:0;border-bottom:1px solid var(--line);} .tb24-foot{flex-direction:column;align-items:stretch;} .tb24-btn{width:100%;} }
</style>

<div class="tb24" id="tb24">
  <div class="tb24-head">
    <h2>Kantteile-Konfigurator</h2>
    <p>Maßanfertigung für Dach und Fassade, exakt nach Ihren Vorgaben gekantet.</p>
  </div>

  <div class="tb24-body">
    <div class="tb24-side">
      <div class="tb24-group">
        <label for="tb24-profil">Kantteil</label>
        <select id="tb24-profil"></select>
      </div>
      <p class="tb24-desc" id="tb24-desc"></p>

      <div class="tb24-dim">
        <h3>Maße</h3>
        <div id="tb24-fields"></div>
      </div>

      <div class="tb24-group">
        <label for="tb24-material">Material</label>
        <select id="tb24-material"></select>
      </div>

      <div class="tb24-group">
        <label id="tb24-farbe-label">Farbe der Ansichtsseite</label>
        <div class="tb24-swatches" id="tb24-farben" role="radiogroup" aria-labelledby="tb24-farbe-label"></div>
      </div>

      <div class="tb24-row">
        <div class="tb24-group">
          <label for="tb24-laenge">Länge (mm)</label>
          <input type="number" id="tb24-laenge" inputmode="numeric" step="10">
        </div>
        <div class="tb24-group">
          <label for="tb24-menge">Stückzahl</label>
          <input type="number" id="tb24-menge" inputmode="numeric" min="1" step="1" value="1">
        </div>
      </div>
    </div>

    <div class="tb24-main">
      <div class="tb24-top">
        <h3>Vorschau</h3>
        <div class="tb24-tabs" role="group" aria-label="Ansicht wählen">
          <button type="button" class="tb24-tab" id="tb24-tab-q" aria-pressed="true">Querschnitt</button>
          <button type="button" class="tb24-tab" id="tb24-tab-3d" aria-pressed="false">3D-Ansicht</button>
        </div>
      </div>
      <div class="tb24-canvas">
        <svg id="tb24-svg" role="img" aria-label="Vorschau des Kantteils" preserveAspectRatio="xMidYMid meet"></svg>
      </div>
      <div class="tb24-legend">
        <span><i id="tb24-chip"></i>Sicht-/Farbseite</span>
        <span><i style="background:#cbd5e1"></i>Rückseite</span>
        <span>Schematische Darstellung, Blechdicke überhöht</span>
      </div>
      <div class="tb24-facts">
        <div><strong>Zuschnitt (Abwicklung):</strong> <span id="tb24-abw">0</span> mm</div>
        <div><strong>Kantungen:</strong> <span id="tb24-biegungen">0</span></div>
        <div><strong>Gesamtlänge:</strong> <span id="tb24-lfm">0</span> m</div>
      </div>
      <div class="tb24-warn" id="tb24-warn" role="alert" hidden></div>
    </div>
  </div>

  <div class="tb24-foot">
    <div>
      <div class="tb24-price" id="tb24-brutto">0,00 €</div>
      <div class="tb24-sub" id="tb24-sub"></div>
    </div>
    <div class="tb24-actions">
      <button type="button" class="tb24-btn alt" id="tb24-share">Link teilen</button>
      <button type="button" class="tb24-btn" id="tb24-cart">In den Warenkorb</button>
    </div>
  </div>
  <div class="tb24-status" id="tb24-status"></div>
  <pre class="tb24-summary" id="tb24-summary"></pre>
</div>

<script>
(function () {
  'use strict';

  /* ===================== EINSTELLUNGEN ===================== */
  const CONFIG = {
    pricePerMeter: 6.50,         // € je Meter Blech, gilt für alle Kantteile
    priceIncludesVat: true,      // true = 6,50 € ist der Endpreis inkl. MwSt.; false = netto, MwSt. wird aufgeschlagen
    vatPercent: 19,
    minLength: 300,              // mm
    maxLength: 3000,             // mm (übliche max. Kantlänge)
    defaultLength: 2000,
    maxUnfold: 1250,             // mm max. Zuschnittbreite (Coil-Breite) – bitte prüfen
    minLeg: 10,                  // mm kürzester Schenkel / Saum
    maxQty: 500,
    storageKey: 'tb24-konfigurator-v1',
    shareParam: 'tb24',
    // Warenkorb: z. B. '/warenkorb/' und cartProductId setzen (WooCommerce)
    cartUrl: '',
    cartProductId: '',
    cartMetaPrefix: 'tb24_',
    allowMailFallback: true,
    mail: 'info@example.de'
  };

  const MATERIALS = [
    { id: 'stahl',    name: 'Stahlblech' },
    { id: 'stahlzn',  name: 'Stahlblech verzinkt' },
    { id: 'alu',      name: 'Aluminium' }
  ];

  const COLORS = [
    { id: '8012', name: 'Rotbraun (RAL 8012)',  hex: '#763b36' },
    { id: '7016', name: 'Anthrazit (RAL 7016)', hex: '#3c3f43' }
  ];

  /* ===================== PROFILE =====================
     Zeichnung als "Schildkröte": start = Anfangsrichtung in Grad (0 = rechts, 90 = nach unten).
     Jeder Schenkel (l = Feld-ID) hat ab dem 2. Schenkel einen Knick:
       turn.a   = Innenwinkel in Grad (Zahl, Feld-ID oder Funktion der Maße)
       turn.dir = +1 Rechtsknick, -1 Linksknick (in Laufrichtung)
     side = Seite der Sicht-/Farbseite: -1 links, +1 rechts der Laufrichtung.
     HEM  = Saum (Falz, parallel zurückgekantet; der Falz-Spalt zählt nicht zum Zuschnitt).
     arcs = Winkelanzeige: 'inner' (Innenwinkel an Schenkel leg) oder 'slope' (Neigung zur Waagerechten). */
  const HEM = -1;                // Marker für Saum/Falz
  const GAP = 2.5;               // mm Abstand der Falz-Schenkel in der Zeichnung
  const L = (id, label, value) => ({ id: id, label: label, value: value });
  const W = (id, label, value, min, max) => ({ id: id, label: label, value: value, angle: true, min: min, max: max });

  const GROUPS = {
    tr:   'Trapezblech / Profilblech',
    sw:   'Sandwichplatten (Kernstärke 40 mm)',
    wand: 'Wand und Ecke'
  };

  const PROFILES = {
    ortgang_tr: {
      group: 'tr', name: 'Ortgangblech',
      desc: 'Seitlicher Abschluss der Dachfläche, schützt vor Durchnässung an Dachrändern und Fassaden. Standardmaße für Trapezprofil 35/207 mit Zusatzkantung. Überlaufschutz optional erhältlich.',
      fields: [L('A', 'Schenkel A', 110), L('B', 'Schenkel B', 264), L('c', 'Kantung c', 14), L('d', 'Saum d', 12), L('e', 'Tropfkante e', 10)],
      start: 135, side: -1,
      legs: [{ l: 'd' }, { l: 'c', turn: { a: HEM, dir: 1 } }, { l: 'A', turn: { a: 135, dir: -1 } }, { l: 'B', turn: { a: 90, dir: 1 } }, { l: 'e', turn: { a: 135, dir: 1 } }]
    },
    pultfirst_tr: {
      group: 'tr', name: 'Pultfirst',
      desc: 'Obere Kante eines Pultdachs: kontrollierte Wasserableitung auf der Dachfläche, verhindert eindringendes Regenwasser. c ist die Dachneigung.',
      fields: [L('A', 'Schenkel A', 110), L('B', 'Schenkel B', 190), W('c', 'Dachneigung c (°)', 10, 0, 45), L('d', 'Kantung d', 15), L('e', 'Saum e', 14), L('f', 'Saum f', 16)],
      start: 135, side: -1,
      legs: [{ l: 'e' }, { l: 'd', turn: { a: HEM, dir: 1 } }, { l: 'A', turn: { a: 135, dir: -1 } },
             { l: 'B', turn: { a: (d) => 90 - d.c, dir: 1 } }, { l: 'f', turn: { a: HEM, dir: 1 } }],
      arcs: [{ type: 'slope', leg: 3, id: 'c' }]
    },
    traufblech: {
      group: 'tr', name: 'Traufblech (Rinneneinhang)',
      desc: 'Unterer Dachabschluss zur Rinne mit kontrollierter Regenwasserableitung, optischer Abschluss der Dachkante von unten. c ist die Dachneigung.',
      fields: [L('A', 'Schenkel A', 70), L('B', 'Schenkel B', 115), W('c', 'Dachneigung c (°)', 10, 0, 45), L('d', 'Kantung d', 15)],
      start: 135, side: -1,
      legs: [{ l: 'd' }, { l: 'A', turn: { a: 45, dir: 1 } }, { l: 'B', turn: { a: (d) => 90 + d.c, dir: 1 } }],
      arcs: [{ type: 'slope', leg: 2, id: 'c' }]
    },
    prallblech_tr: {
      group: 'tr', name: 'Prallblech (Wasserleitblech)',
      desc: 'Verhindert bei starkem Regen das Überschießen von Regenwasser über die Rinne, besonders bei steileren Dächern. c ist die Dachneigung.',
      fields: [L('A', 'Schenkel A', 60), L('B', 'Schenkel B', 115), W('c', 'Dachneigung c (°)', 10, 0, 45), L('d', 'Saum d', 15), L('e', 'Kantung e', 15)],
      start: -135, side: -1,
      legs: [{ l: 'e' }, { l: 'A', turn: { a: 135, dir: 1 } }, { l: 'B', turn: { a: (d) => 90 + d.c, dir: 1 } }, { l: 'd', turn: { a: HEM, dir: 1 } }],
      arcs: [{ type: 'slope', leg: 2, id: 'c' }]
    },

    ortgang_sw: {
      group: 'sw', name: 'Ortgangblech',
      desc: 'Seitlicher Abschluss der Dachfläche für Sandwichplatten. Ein passendes Unterblech wird empfohlen und ist optional, bitte separat bestellen.',
      fields: [L('A', 'Schenkel A', 90), L('B', 'Schenkel B', 90), L('c', 'Verlängerung c', 30), L('d', 'Rückkantung d', 25), L('e', 'Tropfkante e', 15)],
      start: 90, side: -1,
      legs: [{ l: 'd' }, { l: 'c', turn: { a: HEM, dir: 1 } }, { l: 'A', turn: { a: 180, dir: 1 } }, { l: 'B', turn: { a: 90, dir: 1 } }, { l: 'e', turn: { a: 135, dir: 1 } }]
    },
    pultfirst_sw: {
      group: 'sw', name: 'Pultfirst',
      desc: 'Obere Kante eines Pultdachs für Sandwichplatten (Darstellung mit 12° Neigung). Ein passendes Unterblech wird empfohlen und ist optional, bitte separat bestellen.',
      fields: [L('A', 'Schenkel A', 90), L('B', 'Schenkel B', 190), L('c', 'Rückkantung c', 25), L('d', 'Verlängerung d', 30), L('e', 'Saum e', 15)],
      start: 102, side: -1,
      legs: [{ l: 'c' }, { l: 'd', turn: { a: HEM, dir: 1 } }, { l: 'A', turn: { a: 180, dir: 1 } }, { l: 'B', turn: { a: 90, dir: 1 } }, { l: 'e', turn: { a: HEM, dir: 1 } }]
    },
    prallblech_sw: {
      group: 'sw', name: 'Prallblech (Wasserleitblech)',
      desc: 'Verhindert bei starkem Regen das Überschießen von Regenwasser über die Rinne. Standardmaße für Sandwichplatten. c ist die Dachneigung.',
      fields: [L('A', 'Schenkel A', 100), L('B', 'Schenkel B', 115), W('c', 'Dachneigung c (°)', 10, 0, 45), L('d', 'Saum d', 15), L('e', 'Kantung e', 15)],
      start: -135, side: -1,
      legs: [{ l: 'e' }, { l: 'A', turn: { a: 135, dir: 1 } }, { l: 'B', turn: { a: (d) => 90 + d.c, dir: 1 } }, { l: 'd', turn: { a: HEM, dir: 1 } }],
      arcs: [{ type: 'slope', leg: 2, id: 'c' }]
    },

    wandanschluss: {
      group: 'wand', name: 'Wandanschluss',
      desc: 'Verbindung von Dach und Wand mit kontrollierter Ableitung von Regenwasser. Standard ist 90° (senkrecht). Für ein Brustblech in Dachneigung: Winkel = 90° + Dachneigung.',
      fields: [L('A', 'Schenkel A', 120), L('B', 'Schenkel B', 150), L('c', 'Kantung c', 15), L('d', 'Kantung d', 15), W('w', 'Winkel A–B (°)', 90, 45, 170)],
      start: 45, side: -1,
      legs: [{ l: 'c' }, { l: 'A', turn: { a: 135, dir: 1 } }, { l: 'B', turn: { a: 'w', dir: -1 } }, { l: 'd', turn: { a: 135, dir: 1 } }],
      arcs: [{ type: 'inner', leg: 2, id: 'w' }]
    },
    ueberhangschiene: {
      group: 'wand', name: 'Überhangschiene',
      desc: 'Ergänzung zum Wandanschlussblech für eine bessere Ausdehnung des Trapezblechs. Am oberen Ende mit Dichtband (2 bis 3 mm) und Silikonfuge abdichten.',
      fields: [L('A', 'Schenkel A', 35), L('B', 'Schenkel B', 35), L('c', 'Kantung c', 10), L('d', 'Versatz d', 10), L('e', 'Kantung e', 10)],
      start: 135, side: -1, dimPerLeg: true,
      legs: [{ l: 'c' }, { l: 'A', turn: { a: 135, dir: -1 } }, { l: 'd', turn: { a: 135, dir: -1 } }, { l: 'B', turn: { a: 135, dir: 1 } }, { l: 'e', turn: { a: 135, dir: 1 } }]
    },
    eckwinkel_aussen: {
      group: 'wand', name: 'Eckwinkel außen',
      desc: 'Optischer Abschluss von Außenecken, verhindert das Eindringen von Wind oder Insekten. Standard ist 90°, individuell anpassbar.',
      fields: [L('A', 'Schenkel A', 85), L('B', 'Schenkel B', 85), W('c', 'Winkel c (°)', 90, 45, 170), L('d', 'Saum d', 15), L('e', 'Saum e', 15)],
      start: 90, side: -1,
      legs: [{ l: 'e' }, { l: 'A', turn: { a: HEM, dir: 1 } }, { l: 'B', turn: { a: 'c', dir: 1 } }, { l: 'd', turn: { a: HEM, dir: 1 } }],
      arcs: [{ type: 'inner', leg: 2, id: 'c' }]
    },
    eckwinkel_innen: {
      group: 'wand', name: 'Eckwinkel innen',
      desc: 'Optischer Abschluss von Innenecken, verhindert das Eindringen von Wind oder Insekten. Standard ist 90°, individuell anpassbar.',
      fields: [L('A', 'Schenkel A', 85), L('B', 'Schenkel B', 85), W('c', 'Winkel c (°)', 90, 45, 170), L('d', 'Saum d', 15), L('e', 'Saum e', 15)],
      start: 90, side: 1,
      legs: [{ l: 'e' }, { l: 'A', turn: { a: HEM, dir: -1 } }, { l: 'B', turn: { a: 'c', dir: 1 } }, { l: 'd', turn: { a: HEM, dir: -1 } }],
      arcs: [{ type: 'inner', leg: 2, id: 'c' }]
    }
  };

  /* ===================== HILFSFUNKTIONEN ===================== */
  const $ = (id) => document.getElementById('tb24-' + id);
  const eur = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' });
  const num = (v) => { const n = parseFloat(String(v).replace(',', '.')); return isFinite(n) ? n : 0; };
  const SVGNS = 'http://www.w3.org/2000/svg';
  const rad = (deg) => deg * Math.PI / 180;
  const clamp = (v, a, b) => Math.min(Math.max(v, a), b);
  const own = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);

  function el(tag, attrs, text) {
    const e = document.createElementNS(SVGNS, tag);
    for (const k in attrs) e.setAttribute(k, attrs[k]);
    if (text != null) e.textContent = text;
    return e;
  }

  // Farbe abdunkeln (m<1) oder aufhellen (m>1); dunkle Farben bekommen etwas Grundhelligkeit
  function shade(hex, m) {
    const c = [1, 3, 5].map((i) => parseInt(hex.substr(i, 2), 16));
    const out = c.map((v) => clamp(Math.round(v * m + (m - 0.7) * 40), 0, 255));
    return 'rgb(' + out.join(',') + ')';
  }

  let state = { valid: false, data: null, geo: null, view: 'q' };
  let loadMessage = '';

  function setStatus(text, kind) {
    const s = $('status');
    s.className = 'tb24-status' + (kind ? ' ' + kind : '');
    s.textContent = text || '';
  }

  function getCheckedColorId() {
    const node = document.querySelector('input[name="tb24-farbe"]:checked');
    return node ? node.value : COLORS[0].id;
  }

  function setColorById(id) {
    const node = document.querySelector('input[name="tb24-farbe"][value="' + id + '"]');
    if (node) node.checked = true;
  }

  function encodeSharePayload(data) {
    const json = JSON.stringify(data);
    return btoa(unescape(encodeURIComponent(json))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
  }

  function decodeSharePayload(payload) {
    const base = payload.replace(/-/g, '+').replace(/_/g, '/');
    const pad = '='.repeat((4 - (base.length % 4)) % 4);
    const json = decodeURIComponent(escape(atob(base + pad)));
    return JSON.parse(json);
  }

  function readInitialConfig() {
    const p = new URLSearchParams(window.location.search).get(CONFIG.shareParam);
    if (p) {
      try {
        return { source: 'url', value: decodeSharePayload(p) };
      } catch (err) {
        console.warn('Ungültiger Share-Link für den Konfigurator.', err);
        loadMessage = 'Share-Link konnte nicht gelesen werden.';
      }
    }
    try {
      const raw = localStorage.getItem(CONFIG.storageKey);
      if (!raw) return null;
      return { source: 'local', value: JSON.parse(raw) };
    } catch (err) {
      console.warn('Gespeicherte Konfiguration konnte nicht gelesen werden.', err);
      loadMessage = 'Gespeicherte Konfiguration war fehlerhaft.';
      return null;
    }
  }

  function collectConfig() {
    const profileId = $('profil').value;
    const p = PROFILES[profileId];
    if (!p) return null;
    return {
      profil: profileId,
      material: $('material').value,
      farbe: getCheckedColorId(),
      laenge: num($('laenge').value),
      menge: Math.floor(num($('menge').value)),
      view: state.view,
      masse: Object.fromEntries(p.fields.map((f) => [f.id, num($('f-' + f.id).value)]))
    };
  }

  function saveConfig() {
    const cfg = collectConfig();
    if (!cfg) return;
    try {
      localStorage.setItem(CONFIG.storageKey, JSON.stringify(cfg));
    } catch (err) {
      console.warn('Konfiguration konnte nicht gespeichert werden.', err);
      setStatus('Konfiguration konnte lokal nicht gespeichert werden.', 'err');
    }
  }

  function buildShareUrl() {
    const cfg = collectConfig();
    if (!cfg) return '';
    const u = new URL(window.location.href);
    u.searchParams.set(CONFIG.shareParam, encodeSharePayload(cfg));
    return u.toString();
  }

  /* ===================== AUFBAU ===================== */
  function init() {
    const ps = $('profil');
    const groups = {};
    Object.keys(PROFILES).forEach((k) => {
      const p = PROFILES[k];
      if (!groups[p.group]) {
        const og = document.createElement('optgroup');
        og.label = GROUPS[p.group];
        groups[p.group] = og;
        ps.appendChild(og);
      }
      groups[p.group].appendChild(new Option(p.name, k));
    });

    const ms = $('material');
    MATERIALS.forEach((m) => ms.add(new Option(m.name, m.id)));

    const box = $('farben');
    COLORS.forEach((c, i) => {
      const lab = document.createElement('label');
      lab.className = 'tb24-swatch';
      const inp = document.createElement('input');
      inp.type = 'radio'; inp.name = 'tb24-farbe'; inp.value = c.id; inp.checked = i === 0;
      const sp = document.createElement('span');
      sp.style.background = c.hex;
      lab.append(inp, sp, document.createTextNode(c.name));
      box.appendChild(lab);
    });

    const initial = readInitialConfig();
    if (initial && initial.value && PROFILES[initial.value.profil]) ps.value = initial.value.profil;
    if (initial && initial.value && MATERIALS.some((m) => m.id === initial.value.material)) $('material').value = initial.value.material;
    $('laenge').value = initial && initial.value && isFinite(initial.value.laenge) ? initial.value.laenge : CONFIG.defaultLength;
    $('menge').value = initial && initial.value && isFinite(initial.value.menge) ? Math.max(1, Math.floor(initial.value.menge)) : 1;
    if (initial && initial.value) setColorById(initial.value.farbe);

    ps.addEventListener('change', buildFields);
    [ms, $('laenge'), $('menge')].forEach((e) => e.addEventListener('input', update));
    box.addEventListener('change', update);
    $('cart').addEventListener('click', addToCart);
    $('share').addEventListener('click', copyShareLink);
    $('tab-q').addEventListener('click', () => setView('q'));
    $('tab-3d').addEventListener('click', () => setView('3d'));
    buildFields(initial && initial.value ? initial.value.masse : null);
    if (initial && initial.value && initial.value.view === '3d') setView('3d');
    if (loadMessage) setStatus(loadMessage, 'err');
    else if (initial && initial.source === 'url') setStatus('Konfiguration aus Share-Link geladen.', 'ok');
    else if (initial && initial.source === 'local') setStatus('Letzte Konfiguration wurde wiederhergestellt.', 'ok');
  }

  function setView(v) {
    state.view = v;
    $('tab-q').setAttribute('aria-pressed', String(v === 'q'));
    $('tab-3d').setAttribute('aria-pressed', String(v === '3d'));
    render();
    saveConfig();
  }

  function buildFields(initialDims) {
    const p = PROFILES[$('profil').value];
    $('desc').textContent = p.desc + ' Standardmaße sind vorbelegt.';
    const wrap = $('fields');
    wrap.textContent = '';
    p.fields.forEach((f) => {
      const g = document.createElement('div');
      g.className = 'tb24-group';
      const lab = document.createElement('label');
      lab.setAttribute('for', 'tb24-f-' + f.id);
      lab.textContent = f.label + (f.angle ? '' : ' (mm)');
      const inp = document.createElement('input');
      inp.type = 'number'; inp.id = 'tb24-f-' + f.id; inp.value = f.value;
      inp.inputMode = 'decimal'; inp.step = f.angle ? '1' : '5';
      if (f.angle) { inp.min = String(f.min); inp.max = String(f.max); } else inp.min = String(CONFIG.minLeg);
      if (initialDims && own(initialDims, f.id) && isFinite(initialDims[f.id])) inp.value = String(initialDims[f.id]);
      inp.addEventListener('input', update);
      g.append(lab, inp);
      wrap.appendChild(g);
    });
    update();
  }

  /* ===================== BERECHNUNG ===================== */
  function update() {
    const p = PROFILES[$('profil').value];
    const mat = MATERIALS.find((m) => m.id === $('material').value);
    const color = COLORS.find((c) => c.id === document.querySelector('input[name="tb24-farbe"]:checked').value);
    const length = num($('laenge').value);
    const qty = Math.floor(num($('menge').value));

    const d = {};
    const warnings = [];
    let unfold = 0;

    p.fields.forEach((f) => {
      const inp = $('f-' + f.id);
      const v = num(inp.value);
      d[f.id] = v;
      let bad = false;
      if (f.angle) {
        if (v < f.min || v > f.max) { warnings.push(`${f.label}: erlaubt sind ${f.min}° bis ${f.max}°.`); bad = true; }
      } else {
        unfold += v;
        if (v < CONFIG.minLeg) { warnings.push(`${f.label}: mindestens ${CONFIG.minLeg} mm.`); bad = true; }
      }
      inp.classList.toggle('is-bad', bad);
    });

    if (unfold > CONFIG.maxUnfold) warnings.push(`Zuschnittbreite ${unfold} mm überschreitet das Maximum von ${CONFIG.maxUnfold} mm.`);
    const lenBad = length < CONFIG.minLength || length > CONFIG.maxLength;
    if (lenBad) warnings.push(`Länge: ${CONFIG.minLength} bis ${CONFIG.maxLength} mm möglich.`);
    $('laenge').classList.toggle('is-bad', lenBad);
    const qtyBad = qty < 1 || qty > CONFIG.maxQty;
    if (qtyBad) warnings.push(`Stückzahl: 1 bis ${CONFIG.maxQty}.`);
    $('menge').classList.toggle('is-bad', qtyBad);

    // Geometrie (Falz = zwei 90°-Knicke mit kurzem Spalt, der nicht zum Zuschnitt zählt)
    const pts = [[0, 0]], segs = [], legSeg = [];
    let heading = typeof p.start === 'function' ? p.start(d) : p.start, x = 0, y = 0;
    const step = (id, len) => {
      x += len * Math.cos(rad(heading)); y += len * Math.sin(rad(heading));
      pts.push([x, y]); segs.push({ l: id });
    };
    p.legs.forEach((leg) => {
      if (leg.turn) {
        const a = leg.turn.a;
        if (a === HEM) {
          heading += leg.turn.dir * 90; step(null, GAP); heading += leg.turn.dir * 90;
        } else {
          const inner = typeof a === 'string' ? d[a] : typeof a === 'function' ? a(d) : a;
          heading += leg.turn.dir * (180 - inner);
        }
      }
      legSeg.push(segs.length);
      step(leg.l, d[leg.l]);
    });
    state.geo = { p: p, pts: pts, segs: segs, legSeg: legSeg, d: d, hex: color.hex, length: length };
    $('chip').style.background = color.hex;
    $('chip').style.boxShadow = 'inset 0 0 0 1px rgba(15,23,42,.25)';
    render();

    // Preis: fester Preis je Meter für alle Kantteile
    const bends = p.legs.length - 1;
    const meters = (length / 1000) * Math.max(qty, 0);
    const base = CONFIG.pricePerMeter * meters;
    const vat = 1 + CONFIG.vatPercent / 100;
    const gross = CONFIG.priceIncludesVat ? base : base * vat;
    const net = CONFIG.priceIncludesVat ? base / vat : base;

    $('abw').textContent = Math.round(unfold * 10) / 10 + '';
    $('biegungen').textContent = bends;
    $('lfm').textContent = meters.toFixed(2).replace('.', ',');
    $('brutto').textContent = eur.format(gross);
    $('sub').textContent = `inkl. ${CONFIG.vatPercent} % MwSt. · netto ${eur.format(net)} · ${eur.format(CONFIG.pricePerMeter)} je Meter`;

    const w = $('warn');
    w.hidden = warnings.length === 0;
    w.textContent = '';
    if (warnings.length) {
      const ul = document.createElement('ul');
      warnings.forEach((t) => { const li = document.createElement('li'); li.textContent = t; ul.appendChild(li); });
      w.appendChild(ul);
    }

    state.valid = warnings.length === 0;
    $('cart').disabled = !state.valid;
    state.data = {
      profilId: $('profil').value,
      profil: (GROUPS[p.group].split(' (')[0] + ': ' + p.name), masse: p.fields.map((f) => `${f.label.replace(/ \(°\)/, '')}: ${d[f.id]}${f.angle ? '°' : ' mm'}`),
      materialId: mat.id, material: mat.name, farbeId: color.id, farbe: color.name, laenge: length, menge: qty,
      abwicklung: unfold, biegungen: bends, netto: net, brutto: gross, masseWerte: d
    };
    saveConfig();
  }

  /* ===================== VORSCHAU: GEOMETRIE ===================== */
  // Blech mit Dicke t: P = Rückseite, Q = Sicht-/Farbseite, N = Normalen je Schenkel (zeigen zur Farbseite)
  function outline(pts, t, side, perLeg) {
    const n = pts.length;
    const N = [];
    // side = -1: Farbseite links der Laufrichtung, +1: rechts
    for (let i = 0; i < n - 1; i++) {
      const dx = pts[i + 1][0] - pts[i][0], dy = pts[i + 1][1] - pts[i][1];
      const Ln = Math.hypot(dx, dy) || 1;
      N.push([side * (-dy / Ln), side * (dx / Ln)]);
    }

    // Maßlinien liegen immer außen (weg vom Schwerpunkt), unabhängig von der Farbseite
    let cx = 0, cy = 0, score = 0;
    pts.forEach((q) => { cx += q[0]; cy += q[1]; });
    cx /= n; cy /= n;
    for (let i = 0; i < n - 1; i++) {
      const mx = (pts[i][0] + pts[i + 1][0]) / 2 - cx, my = (pts[i][1] + pts[i + 1][1]) / 2 - cy;
      const len = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]);
      score += len * (N[i][0] * mx + N[i][1] * my);  // N zeigt zur Farbseite; lange Schenkel zählen mehr
    }
    const ds = score >= 0 ? 1 : -1;                  // 1 = Farbseite ist außen
    const D = N.map((v, i) => {
      if (!perLeg) return [v[0] * ds, v[1] * ds];       // alle Maßlinien auf derselben Seite
      const mx = (pts[i][0] + pts[i + 1][0]) / 2 - cx, my = (pts[i][1] + pts[i + 1][1]) / 2 - cy;
      const sg = (v[0] * mx + v[1] * my) >= 0 ? 1 : -1; // versetzte Profile: je Schenkel nach außen
      return [v[0] * sg, v[1] * sg];
    });

    const Q = pts.map((q, k) => {
      if (k === 0) return [q[0] + N[0][0] * t, q[1] + N[0][1] * t];
      if (k === n - 1) return [q[0] + N[n - 2][0] * t, q[1] + N[n - 2][1] * t];
      let mx = N[k - 1][0] + N[k][0], my = N[k - 1][1] + N[k][1];
      const l = Math.hypot(mx, my);
      if (l < 1e-6) {                         // exakte Umkehr: Nase in Laufrichtung
        const tx = q[0] - pts[k - 1][0], ty = q[1] - pts[k - 1][1], tl = Math.hypot(tx, ty) || 1;
        return [q[0] + tx / tl * t, q[1] + ty / tl * t];
      }
      mx /= l; my /= l;
      const dt = mx * N[k][0] + my * N[k][1];
      const f = dt < 0.25 ? t : Math.min(t / dt, 3 * t);   // Saum: Nase; sonst Gehrung
      return [q[0] + mx * f, q[1] + my * f];
    });
    return { P: pts, Q: Q, N: N, D: D };
  }

  function bounds(list) {
    const xs = list.map((q) => q[0]), ys = list.map((q) => q[1]);
    return { minX: Math.min.apply(null, xs), maxX: Math.max.apply(null, xs), minY: Math.min.apply(null, ys), maxY: Math.max.apply(null, ys) };
  }

  // Bildausschnitt im Seitenverhältnis 3:2, zentriert
  function frame(b, pad) {
    let W = b.maxX - b.minX + 2 * pad, H = b.maxY - b.minY + 2 * pad;
    if (W / H > 1.5) H = W / 1.5; else W = H * 1.5;
    return { x: (b.minX + b.maxX) / 2 - W / 2, y: (b.minY + b.maxY) / 2 - H / 2, W: W, H: H, fs: W * 0.028 };
  }

  function defs(svg, fr, hex, b) {
    svg.insertAdjacentHTML('beforeend',
      '<defs>' +
      '<linearGradient id="tb24-grad" gradientUnits="userSpaceOnUse" x1="' + b.minX + '" y1="' + b.minY + '" x2="' + b.maxX + '" y2="' + b.maxY + '">' +
        '<stop offset="0" stop-color="' + shade(hex, 1.22) + '"/><stop offset=".45" stop-color="' + shade(hex, 0.95) + '"/>' +
        '<stop offset=".7" stop-color="' + shade(hex, 1.1) + '"/><stop offset="1" stop-color="' + shade(hex, 0.8) + '"/></linearGradient>' +
      '<marker id="tb24-arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">' +
        '<path d="M0 1 L10 5 L0 9 z" fill="#475569"/></marker>' +
      '<filter id="tb24-shadow" x="-20%" y="-20%" width="150%" height="150%">' +
        '<feDropShadow dx="' + fr.fs * 0.15 + '" dy="' + fr.fs * 0.3 + '" stdDeviation="' + fr.fs * 0.35 + '" flood-color="#0f172a" flood-opacity=".28"/></filter>' +
      '</defs>');
  }

  function pill(svg, x, y, txt, fs, color) {
    const w = txt.length * fs * 0.6 + fs * 0.9, h = fs * 1.55;
    svg.appendChild(el('rect', { x: x - w / 2, y: y - h / 2, width: w, height: h, rx: h / 2, fill: '#fff', 'fill-opacity': '.95', stroke: '#cbd5e1', 'stroke-width': fs * 0.05 }));
    svg.appendChild(el('text', { x: x, y: y + fs * 0.36, 'text-anchor': 'middle', 'font-size': fs, 'font-weight': '600', fill: color || '#0f172a', 'font-family': 'inherit' }, txt));
  }

  function dimLine(svg, a, b, fs) {
    const len = Math.hypot(b[0] - a[0], b[1] - a[1]);
    const att = { x1: a[0], y1: a[1], x2: b[0], y2: b[1], stroke: '#475569', 'stroke-width': fs * 0.07 };
    if (len > fs * 2.6) { att['marker-start'] = 'url(#tb24-arr)'; att['marker-end'] = 'url(#tb24-arr)'; }
    svg.appendChild(el('line', att));
  }

  function angleArc(svg, V, A, B, minLen, fs, txt, labelAt) {
    const nrm = (a) => { const l = Math.hypot(a[0] - V[0], a[1] - V[1]) || 1; return [(a[0] - V[0]) / l, (a[1] - V[1]) / l]; };
    const u = nrm(A), v = nrm(B);
    const r = clamp(minLen * 0.3, fs * 2, fs * 5);
    const sweep = (u[0] * v[1] - u[1] * v[0]) > 0 ? 1 : 0;
    const p1 = [V[0] + u[0] * r, V[1] + u[1] * r], p2 = [V[0] + v[0] * r, V[1] + v[1] * r];
    svg.appendChild(el('path', {
      d: `M${p1[0].toFixed(2)} ${p1[1].toFixed(2)} A${r.toFixed(2)} ${r.toFixed(2)} 0 0 ${sweep} ${p2[0].toFixed(2)} ${p2[1].toFixed(2)}`,
      fill: 'none', stroke: '#ea580c', 'stroke-width': fs * 0.1, 'stroke-linecap': 'round'
    }));
    const dot = u[0] * v[0] + u[1] * v[1];
    let px, py;
    if (labelAt) { px = labelAt[0]; py = labelAt[1]; }
    else if (dot > 0.82) {                  // schmaler Winkel: Schild neben den Bogen setzen
      let wx = v[0] - u[0] * dot, wy = v[1] - u[1] * dot;
      const wl = Math.hypot(wx, wy) || 1; wx /= wl; wy /= wl;
      px = V[0] + u[0] * (r + fs * 2.6) - wx * fs * 1.2;
      py = V[1] + u[1] * (r + fs * 2.6) - wy * fs * 1.2;
    } else {
      let bx = u[0] + v[0], by = u[1] + v[1];
      const bl = Math.hypot(bx, by);
      if (bl < 0.05) { bx = -u[1]; by = u[0]; } else { bx /= bl; by /= bl; }
      px = V[0] + bx * (r + fs * 1.5); py = V[1] + by * (r + fs * 1.5);
    }
    pill(svg, px, py, txt, fs, '#c2410c');
  }

  const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);

  /* ===================== VORSCHAU: QUERSCHNITT ===================== */
  function draw2d(g) {
    const svg = $('svg');
    svg.textContent = '';
    svg.setAttribute('aria-label', 'Querschnitt: ' + g.p.name);

    const b0 = bounds(g.pts);
    const size = Math.max(b0.maxX - b0.minX, b0.maxY - b0.minY, 40);
    const t = Math.max(size * 0.024, 1.4);
    const o = outline(g.pts, t, g.p.side, g.p.dimPerLeg);
    const b = bounds(g.pts.concat(o.Q));
    const fr = frame(b, Math.max(size * 0.3, 25));
    svg.setAttribute('viewBox', [fr.x, fr.y, fr.W, fr.H].join(' '));
    defs(svg, fr, g.hex, b);
    const fs = fr.fs, off = t + fs * 1.8;
    const fmt = (arr) => arr.map((q, i) => (i ? 'L' : 'M') + q[0].toFixed(2) + ' ' + q[1].toFixed(2)).join(' ');

    // Blechkörper
    const poly = o.P.concat(o.Q.slice().reverse());
    const body = el('g', { filter: 'url(#tb24-shadow)' });
    body.appendChild(el('path', { d: fmt(poly) + ' Z', fill: 'url(#tb24-grad)', stroke: shade(g.hex, 0.5), 'stroke-width': t * 0.14, 'stroke-linejoin': 'round' }));
    svg.appendChild(body);
    // Rückseite (hellgrau) und Glanzlinie auf der Sicht-/Farbseite
    svg.appendChild(el('path', { d: fmt(o.P), fill: 'none', stroke: '#cbd5e1', 'stroke-width': t * 0.32, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }));
    const hl = o.Q.map((q, i) => [q[0] + (o.P[i][0] - q[0]) * 0.22, q[1] + (o.P[i][1] - q[1]) * 0.22]);
    svg.appendChild(el('path', { d: fmt(hl), fill: 'none', stroke: '#fff', 'stroke-opacity': '.35', 'stroke-width': t * 0.16, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }));

    // Bemaßung (Falz-Spalte werden nicht bemaßt)
    g.segs.forEach((sg, i) => {
      if (!sg.l) return;
      const n = o.D[i], A = o.P[i], B = o.P[i + 1];
      const a2 = [A[0] + n[0] * off, A[1] + n[1] * off], b2 = [B[0] + n[0] * off, B[1] + n[1] * off];
      [[A, a2], [B, b2]].forEach((e) => {
        svg.appendChild(el('line', {
          x1: e[0][0] + n[0] * t * 1.8, y1: e[0][1] + n[1] * t * 1.8, x2: e[1][0] + n[0] * fs * 0.4, y2: e[1][1] + n[1] * fs * 0.4,
          stroke: '#94a3b8', 'stroke-width': fs * 0.05, 'stroke-dasharray': (fs * 0.3) + ' ' + (fs * 0.2)
        }));
      });
      dimLine(svg, a2, b2, fs);
    });
    g.segs.forEach((sg, i) => {
      if (!sg.l) return;
      const n = o.D[i], A = o.P[i], B = o.P[i + 1];
      pill(svg, (A[0] + B[0]) / 2 + n[0] * off, (A[1] + B[1]) / 2 + n[1] * off, sg.l + '  ' + g.d[sg.l], fs);
    });

    // Winkel: Innenwinkel oder Neigung zur Waagerechten
    (g.p.arcs || []).forEach((ar) => {
      const j = g.legSeg[ar.leg], V = o.P[j];
      if (ar.type === 'inner') {
        angleArc(svg, V, o.P[j - 1], o.P[j + 1], Math.min(dist(o.P[j], o.P[j - 1]), dist(o.P[j], o.P[j + 1])), fs, ar.id + '  ' + g.d[ar.id] + '°');
      } else {
        const Bp = o.P[j + 1], lenB = dist(V, Bp), sx = Bp[0] >= V[0] ? 1 : -1;
        const ref = [V[0] + sx * lenB * 0.9, V[1]];
        svg.appendChild(el('line', { x1: V[0], y1: V[1], x2: ref[0], y2: ref[1], stroke: '#94a3b8', 'stroke-width': fs * 0.07, 'stroke-dasharray': (fs * 0.5) + ' ' + (fs * 0.35) }));
        // Schild auf der Seite, die der Maßlinie von B gegenüberliegt
        const r = clamp(lenB * 0.3, fs * 2, fs * 5);
        const lx = V[0] + sx * (r + fs * 2.8);
        const yB = V[1] + (Bp[1] - V[1]) * ((lx - V[0]) / ((Bp[0] - V[0]) || 1));
        const below = o.D[j][1] <= 0;
        const ly = below ? Math.max(V[1], yB) + fs * 1.5 : Math.min(V[1], yB) - fs * 1.5;
        angleArc(svg, V, ref, Bp, lenB, fs, ar.id + '  ' + g.d[ar.id] + '°', [lx, ly]);
      }
    });
  }

  /* ===================== VORSCHAU: 3D (schräge Parallelprojektion) ===================== */
  function draw3d(g) {
    const svg = $('svg');
    svg.textContent = '';
    svg.setAttribute('aria-label', '3D-Ansicht: ' + g.p.name);

    const b0 = bounds(g.pts);
    const size = Math.max(b0.maxX - b0.minX, b0.maxY - b0.minY, 40);
    const t = Math.max(size * 0.024, 1.4);
    const o = outline(g.pts, t, g.p.side, g.p.dimPerLeg);
    const n = g.pts.length;
    const poly = o.P.concat(o.Q.slice().reverse());

    const D = size * clamp(g.length / size * 0.35, 0.5, 1.6);
    const e = [0.866 * D, -0.5 * D];
    const front = bounds(poly);
    const S = [front.maxX + size * 0.08, front.maxY + size * 0.1];
    const all = poly.concat(poly.map((q) => [q[0] + e[0], q[1] + e[1]]), [S, [S[0] + e[0], S[1] + e[1]]]);
    const b = bounds(all);
    const fr = frame(b, Math.max(size * 0.22, 20));
    svg.setAttribute('viewBox', [fr.x, fr.y, fr.W, fr.H].join(' '));
    defs(svg, fr, g.hex, front);
    const fs = fr.fs;

    let area = 0;
    for (let k = 0; k < poly.length; k++) {
      const a = poly[k], c = poly[(k + 1) % poly.length];
      area += a[0] * c[1] - c[0] * a[1];
    }
    const Lg = [-0.35, -0.94];
    const quads = [];
    for (let k = 0; k < poly.length; k++) {
      const a = poly[k], c = poly[(k + 1) % poly.length];
      const tx = c[0] - a[0], ty = c[1] - a[1];
      const tl = Math.hypot(tx, ty);
      if (tl < 1e-6) continue;
      const nx = (area > 0 ? ty : -ty) / tl, ny = (area > 0 ? -tx : tx) / tl;
      if (nx * e[0] + ny * e[1] <= 0) continue;
      const base = k < n - 1 ? '#9aa4b2' : (k === n - 1 || k === 2 * n - 1) ? '#b8c0cc' : g.hex;
      const m = 0.6 + 0.55 * Math.max(0, nx * Lg[0] + ny * Lg[1]);
      quads.push([a, c, [c[0] + e[0], c[1] + e[1]], [a[0] + e[0], a[1] + e[1]], shade(base, m)]);
    }
    const gq = el('g', { filter: 'url(#tb24-shadow)' });
    quads.forEach((q) => {
      const d = 'M' + q.slice(0, 4).map((p) => p[0].toFixed(2) + ' ' + p[1].toFixed(2)).join(' L') + ' Z';
      gq.appendChild(el('path', { d: d, fill: q[4], stroke: q[4], 'stroke-width': t * 0.1, 'stroke-linejoin': 'round' }));
    });
    svg.appendChild(gq);

    const pathFront = 'M' + poly.map((q) => q[0].toFixed(2) + ' ' + q[1].toFixed(2)).join(' L') + ' Z';
    svg.appendChild(el('path', { d: pathFront, fill: 'url(#tb24-grad)', stroke: shade(g.hex, 0.5), 'stroke-width': t * 0.14, 'stroke-linejoin': 'round' }));

    const S2 = [S[0] + e[0], S[1] + e[1]];
    dimLine(svg, S, S2, fs);
    pill(svg, (S[0] + S2[0]) / 2, (S[1] + S2[1]) / 2, g.length + ' mm', fs);
  }

  function render() {
    if (!state.geo) return;
    if (state.view === '3d') draw3d(state.geo); else draw2d(state.geo);
  }

  /* ===================== WARENKORB ===================== */
  function addToCart() {
    if (!state.valid) return;
    const s = state.data;
    const text = [
      `Kantteil: ${s.profil}`, ...s.masse, `Zuschnitt (Abwicklung): ${s.abwicklung} mm`,
      `Länge: ${s.laenge} mm`, `Stückzahl: ${s.menge}`, `Material: ${s.material}`, `Farbe: ${s.farbe}`,
      `Preis: ${eur.format(s.brutto)} brutto`
    ].join('\n');

    const hasCartTarget = Boolean(CONFIG.cartUrl || CONFIG.cartProductId);
    if (hasCartTarget) {
      const f = document.createElement('form');
      f.method = 'POST'; f.action = CONFIG.cartUrl || window.location.pathname; f.style.display = 'none';
      const add = (n, v) => { const i = document.createElement('input'); i.type = 'hidden'; i.name = n; i.value = v; f.appendChild(i); };
      const prefix = CONFIG.cartMetaPrefix || 'tb24_';
      const meta = {
        profil_id: s.profilId,
        profil_name: s.profil,
        material_id: s.materialId,
        material_name: s.material,
        farbe_id: s.farbeId,
        farbe_name: s.farbe,
        laenge_mm: s.laenge,
        menge: s.menge,
        abwicklung_mm: s.abwicklung,
        biegungen: s.biegungen,
        netto_eur: Number(s.netto.toFixed(2)),
        brutto_eur: Number(s.brutto.toFixed(2)),
        masse_json: JSON.stringify(s.masseWerte)
      };

      if (CONFIG.cartProductId) add('add-to-cart', CONFIG.cartProductId);
      add('quantity', s.menge);
      Object.keys(meta).forEach((k) => add(prefix + k, meta[k]));
      add(prefix + 'summary', text);
      add(prefix + 'json', JSON.stringify(meta));
      document.body.appendChild(f);
      f.submit();
      return;
    }

    const out = $('summary');
    out.style.display = 'block';
    out.textContent = text + '\n\n';
    if (CONFIG.allowMailFallback) {
      const a = document.createElement('a');
      a.href = 'mailto:' + CONFIG.mail + '?subject=' + encodeURIComponent('Anfrage Kantteil') + '&body=' + encodeURIComponent(text);
      a.textContent = 'Konfiguration per E-Mail anfragen';
      a.style.fontWeight = '700';
      out.appendChild(a);
      setStatus('Kein Warenkorb-Ziel konfiguriert – E-Mail-Fallback aktiv.', 'err');
    } else {
      setStatus('Kein Warenkorb-Ziel konfiguriert. Bitte cartUrl/cartProductId setzen.', 'err');
    }
  }

  function copyShareLink() {
    const url = buildShareUrl();
    if (!url) {
      setStatus('Share-Link konnte nicht erstellt werden.', 'err');
      return;
    }
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(url).then(
        () => setStatus('Share-Link in die Zwischenablage kopiert.', 'ok'),
        (err) => {
          console.warn('Share-Link konnte nicht in die Zwischenablage kopiert werden.', err);
          const out = $('summary');
          out.style.display = 'block';
          out.textContent = 'Share-Link:\n' + url;
          setStatus('Zwischenablage nicht verfügbar – Link unten manuell kopieren.', 'err');
        }
      );
      return;
    }
    const out = $('summary');
    out.style.display = 'block';
    out.textContent = 'Share-Link:\n' + url;
    setStatus('Zwischenablage nicht verfügbar – Link unten manuell kopieren.', 'err');
  }

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }})();
</script>

Kantteile-Konfigurator

Maßanfertigung für Dach und Fassade, exakt nach Ihren Vorgaben gekantet.

Maße

Vorschau

Sicht-/Farbseite Rückseite Schematische Darstellung, Blechdicke überhöht
Zuschnitt (Abwicklung): 0 mm
Kantungen: 0
Gesamtlänge: 0 m
0,00 €