/* Powermieter — animated visuals
   A) EnergyFlowIllustration — "Stromfluss-Loop" (Energiehaus)
   B) ProcessSequence       — "Vom Aushang zum Vertrag"
   Both export to window. */
const { useState: useAnState, useEffect: useAnEffect } = React;

/* ============================================================ A) FLOW ==== */
function EnergyFlowIllustration() {
  const cols = [158, 210, 262];                 // three riser columns
  const rowY = [138, 184, 230, 276];            // four apartment floors

  const solarDots = [];
  cols.forEach((x, ci) => {
    for (let k = 0; k < 3; k++) solarDots.push({ x, key: `s${ci}${k}`, begin: (ci * 0.55 + k * 1.0).toFixed(2) });
  });
  const windows = [];
  cols.forEach((cx, ci) => rowY.forEach((y, ri) => windows.push({ x: cx - 16, y, key: `w${ci}${ri}`, delay: ((ci + ri) % 5) * 0.6 })));

  return (
    <svg className="pm-flow" viewBox="0 0 420 360" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
      <defs>
        <linearGradient id="pmf-body" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#1C2E48" /><stop offset="1" stopColor="#0B1424" />
        </linearGradient>
        <linearGradient id="pmf-beam" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="var(--accent-400)" stopOpacity="0.42" />
          <stop offset="1" stopColor="var(--accent-400)" stopOpacity="0" />
        </linearGradient>
        <radialGradient id="pmf-sun" cx="0.5" cy="0.45" r="0.55">
          <stop offset="0" stopColor="var(--accent-200)" /><stop offset="1" stopColor="var(--accent-500)" />
        </radialGradient>
      </defs>

      {/* sun */}
      <circle cx="358" cy="62" r="40" fill="var(--accent-400)" opacity="0.12" />
      <circle cx="358" cy="62" r="21" fill="url(#pmf-sun)" />

      {/* utility pole + backup wire (Netz) */}
      <g stroke="var(--text-3)" strokeWidth="2" fill="none" opacity="0.55" strokeLinecap="round">
        <line x1="46" y1="248" x2="46" y2="322" />
        <line x1="33" y1="260" x2="59" y2="260" />
        <line x1="36" y1="272" x2="56" y2="272" />
        <path d="M46 322 L120 322" />
      </g>

      {/* energy beams behind risers */}
      {cols.map((x, i) => (<rect key={i} x={x - 9} y="110" width="18" height="214" fill="url(#pmf-beam)" />))}

      {/* building body */}
      <rect x="120" y="110" width="180" height="220" rx="11" fill="url(#pmf-body)" stroke="#2A3F5D" strokeWidth="1.5" />

      {/* solar roof band */}
      <rect x="106" y="80" width="208" height="30" rx="8" fill="#0A1322" stroke="var(--accent-400)" strokeOpacity="0.35" strokeWidth="1.5" />
      {Array.from({ length: 9 }).map((_, i) => (
        <rect key={i} className="pm-pv" x={114 + i * 21.5} y="86" width="16.5" height="18" rx="2.5"
          fill="var(--accent-400)" style={{ animationDelay: (i * 0.22) + 's' }} />
      ))}

      {/* apartment windows */}
      {windows.map(w => (
        <rect key={w.key} className="pm-win" x={w.x} y={w.y} width="32" height="30" rx="5"
          fill="var(--accent-400)" stroke="#2A3F5D" strokeWidth="1" style={{ animationDelay: w.delay + 's' }} />
      ))}

      {/* door */}
      <rect x="196" y="298" width="28" height="32" rx="4" fill="#0A1322" stroke="#2A3F5D" strokeWidth="1" />

      {/* solar flowing light points (roof → apartments) */}
      {solarDots.map(d => (
        <circle key={d.key} r="3.4" fill="var(--accent-300)">
          <animateMotion dur="3s" begin={d.begin + 's'} repeatCount="indefinite" path={`M${d.x},106 L${d.x},322`} />
          <animate attributeName="opacity" dur="3s" begin={d.begin + 's'} repeatCount="indefinite" values="0;1;1;0" keyTimes="0;0.12;0.85;1" />
        </circle>
      ))}

      {/* backup grid flow (Netz → building) */}
      {[0, 1.3].map((b, i) => (
        <circle key={i} r="2.8" fill="var(--text-3)">
          <animateMotion dur="2.6s" begin={b + 's'} repeatCount="indefinite" path="M46,260 L46,322 L120,322" />
          <animate attributeName="opacity" dur="2.6s" begin={b + 's'} repeatCount="indefinite" values="0;0.85;0.85;0" keyTimes="0;0.18;0.8;1" />
        </circle>
      ))}
    </svg>
  );
}

/* ======================================================= B) SEQUENCE ===== */
const SEQ_SCENES = [
  { ic: 'note',      t: 'Aushang im Treppenhaus', d: 'Im Hausflur hängt ein Aushang Ihrer Hausverwaltung mit einem QR-Code für Ihr Gebäude.' },
  { ic: 'qr',        t: 'QR-Code scannen',        d: 'Sie scannen den Code mit dem Smartphone – ganz ohne App-Installation oder Anmeldung.' },
  { ic: 'external',  t: 'Ihre Seite öffnet sich', d: 'Die Powermieter-Seite für genau Ihre Adresse wird geladen – mit allen Infos zum Angebot.' },
  { ic: 'user',      t: 'Interesse anmelden',     d: 'In wenigen Minuten tragen Sie Ihre Daten ein. Unverbindlich und jederzeit pausierbar.' },
  { ic: 'signature', t: 'Vertrag digital bestätigen', d: 'Sie prüfen die Unterlagen in Ruhe und schließen den Vertrag rechtssicher digital ab.' },
  { ic: 'chart',     t: 'Portal & Abrechnung',    d: 'Im Portal sehen Sie Verbrauch, Solaranteil und Ihre transparenten Abrechnungen.' },
];

function SeqPhone({ scan, children }) {
  return (
    <div className="pm-seq-phone">
      <span className="pm-seq-phone-notch" />
      <div className="pm-seq-phone-scr">{children}</div>
      {scan && <span className="pm-seq-scanline" />}
    </div>
  );
}

function SeqVisual({ i }) {
  if (i === 0) return (
    <div className="pm-seq-poster">
      <span className="pm-seq-pin" />
      <div className="pm-seq-poster-top"><Logo size={19} /></div>
      <div className="pm-seq-poster-h">Solarstrom vom Dach nutzen</div>
      <div className="pm-seq-qr"><QRGlyph size={82} /></div>
      <div className="pm-seq-poster-sub">Musterstraße 12 · jetzt informieren</div>
    </div>
  );
  if (i === 1) return (
    <div className="pm-seq-scan-wrap">
      <div className="pm-seq-poster"><div className="pm-seq-qr" style={{ margin: '4px 0' }}><QRGlyph size={64} /></div></div>
      <SeqPhone scan><div className="pm-seq-cam"><QRGlyph size={66} /></div></SeqPhone>
    </div>
  );
  if (i === 2) return (
    <SeqPhone>
      <div className="pm-seq-statusbar" />
      <div className="pm-seq-hero" />
      <div className="pm-seq-l w90" /><div className="pm-seq-l w70" /><div className="pm-seq-l w50" />
      <div className="pm-seq-cta">Interesse anmelden</div>
    </SeqPhone>
  );
  if (i === 3) return (
    <SeqPhone>
      <div className="pm-seq-statusbar" />
      <div className="pm-seq-l w50" style={{ height: 6 }} />
      <div className="pm-seq-input" />
      <div className="pm-seq-l w50" style={{ height: 6 }} />
      <div className="pm-seq-input" data-focus="true" style={{ position: 'relative' }}><span className="pm-seq-caret" /></div>
      <div className="pm-seq-l w50" style={{ height: 6 }} />
      <div className="pm-seq-input" />
      <div className="pm-seq-cta">Weiter</div>
    </SeqPhone>
  );
  if (i === 4) return (
    <SeqPhone>
      <div className="pm-seq-statusbar" />
      <div className="pm-seq-checkbadge"><I.check sw={2.6} size={24} /></div>
      <div className="pm-seq-done-t">Vertrag bestätigt</div>
      <div className="pm-seq-doc" style={{ marginTop: 8 }}>
        <div className="pm-seq-l w90" /><div className="pm-seq-l w70" /><div className="pm-seq-l w90" /><div className="pm-seq-l w50" />
      </div>
    </SeqPhone>
  );
  return (
    <SeqPhone>
      <div className="pm-seq-portal-top">
        <span className="pm-seq-pill">Aktiv</span>
        <I.leaf size={15} style={{ color: 'var(--positive)' }} />
      </div>
      <div style={{ marginTop: 6 }}>
        <div className="pm-seq-l w50" style={{ height: 6, marginBottom: 6 }} />
        <div className="pm-seq-big">73<span>%</span></div>
        <div className="pm-seq-l w70" style={{ height: 6, marginTop: 6 }} />
      </div>
      <div className="pm-seq-bars">{[42, 64, 50, 78, 73, 60, 85].map((h, k) => <i key={k} style={{ height: h + '%', animationDelay: (k * 0.06) + 's' }} />)}</div>
    </SeqPhone>
  );
}

function ProcessSequence() {
  const [i, setI] = useAnState(0);
  const [paused, setPaused] = useAnState(false);
  useAnEffect(() => {
    if (paused) return;
    const t = setInterval(() => setI(p => (p + 1) % SEQ_SCENES.length), 2700);
    return () => clearInterval(t);
  }, [paused]);

  const sc = SEQ_SCENES[i];
  return (
    <div className="pm-seq"
      onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      <div className="pm-seq-stage">
        <div className="pm-seq-device">
          <div className="pm-seq-scene" key={i}><SeqVisual i={i} /></div>
        </div>
        <div className="pm-seq-caption">
          <div className="pm-seq-caption-in" key={'c' + i}>
            <span className="pm-seq-step">Schritt {i + 1} von {SEQ_SCENES.length}</span>
            <div className="pm-seq-title">{sc.t}</div>
            <p className="pm-seq-desc">{sc.d}</p>
          </div>
        </div>
      </div>

      <div className="pm-seq-track">
        {SEQ_SCENES.map((s, n) => {
          const Ic = I[s.ic];
          const state = n < i ? 'done' : n === i ? 'active' : 'todo';
          return (
            <React.Fragment key={n}>
              <button className="pm-seq-node" data-state={state} onClick={() => setI(n)} aria-label={s.t} title={s.t}>
                <span className="pm-seq-node-dot">{n < i ? <I.check size={17} /> : <Ic size={18} />}</span>
                <span className="pm-seq-node-l">{s.t}</span>
              </button>
              {n < SEQ_SCENES.length - 1 && <span className="pm-seq-line" data-done={n < i ? 'true' : 'false'}><span /></span>}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

/* ============================== C) SAVINGS COMPARISON (animated bars) ===== */
function pmEur(n) { return n.toLocaleString('de-DE', { minimumFractionDigits: 0, maximumFractionDigits: 0 }); }

function SavingsComparison({ gv, pm, ersparnis, verbrauch }) {
  const max = Math.max(gv, pm, 1);
  const w = v => (v / max * 100).toFixed(1) + '%';

  return (
    <div className="card card-pad pm-cmp">
      <div className="pm-card-head" style={{ marginBottom: 18 }}>
        <h3 className="pm-card-title"><I.chart size={18} /> Ihr Kostenvergleich pro Jahr</h3>
        <span className="chip chip-positive"><I.leaf size={13} /> ≈ {ersparnis} € sparen</span>
      </div>

      <div className="pm-cmp-row">
        <div className="pm-cmp-label">Klassische<br />Grundversorgung</div>
        <div className="pm-cmp-track"><span className="pm-cmp-fill pm-cmp-gv" style={{ width: w(gv) }} /></div>
        <div className="pm-cmp-cap">{pmEur(gv)} €</div>
      </div>

      <div className="pm-cmp-row">
        <div className="pm-cmp-label">Powermieter<br />Lokalstrom</div>
        <div className="pm-cmp-track"><span className="pm-cmp-fill pm-cmp-pm" style={{ width: w(pm) }} /></div>
        <div className="pm-cmp-cap">{pmEur(pm)} €</div>
      </div>

      <div className="pm-cmp-row pm-cmp-row-save">
        <div className="pm-cmp-label">Ihre mögliche<br />Ersparnis</div>
        <div className="pm-cmp-track"><span className="pm-cmp-fill pm-cmp-save" style={{ width: w(Math.max(0, gv - pm)) }} /></div>
        <div className="pm-cmp-cap pm-cmp-cap-save">≈ {ersparnis} €</div>
      </div>

      <p className="pm-cmp-note"><I.info size={14} /> Beispielrechnung bei {verbrauch.toLocaleString('de-DE')} kWh/Jahr. Die tatsächliche Ersparnis hängt von Ihrem Verbrauch, dem Tarif und dem Solaranteil im Gebäude ab.</p>
    </div>
  );
}

/* ============================== D) METER-NUMBER HELP MODAL ================ */
function MeterNumberHelpModal({ onClose }) {
  return (
    <div className="pm-modal" onClick={onClose}>
      <div className="pm-modal-inner pm-modal-help" onClick={e => e.stopPropagation()}>
        <div className="pm-modal-bar">
          <span style={{ fontWeight: 600, color: 'var(--text)' }}>Wo finde ich meine Zählernummer?</span>
          <button className="pm-iconbtn" onClick={onClose} aria-label="Schließen"><I.x size={18} /></button>
        </div>
        <div className="pm-help-body">
          <div className="pm-help-illu">
            <svg viewBox="0 0 280 220" width="100%" aria-hidden="true">
              <defs>
                <linearGradient id="pmm-face" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="var(--surface)" /><stop offset="1" stopColor="var(--surface-2)" /></linearGradient>
              </defs>
              {/* meter body */}
              <rect x="40" y="20" width="200" height="180" rx="16" fill="url(#pmm-face)" stroke="var(--border-strong)" strokeWidth="2" />
              <rect x="40" y="20" width="200" height="40" rx="16" fill="var(--surface-3)" />
              <text x="60" y="46" fontFamily="var(--font-sans)" fontSize="12" fontWeight="700" fill="var(--text-2)">eHZ · Stromzähler</text>
              {/* digital reading */}
              <rect x="60" y="74" width="160" height="34" rx="6" fill="var(--navy-900)" />
              {[0,1,2,3,4].map(i => <rect key={i} x={68 + i*22} y="80" width="17" height="22" rx="2" fill="#0F2A33" />)}
              {'02947'.split('').map((d,i) => <text key={i} x={76 + i*22} y="98" fontFamily="var(--font-mono)" fontSize="16" fontWeight="600" fill="var(--accent-300)" textAnchor="middle">{d}</text>)}
              <text x="216" y="98" fontFamily="var(--font-mono)" fontSize="11" fill="var(--accent-300)" textAnchor="end">kWh</text>
              {/* barcode */}
              <g>
                {Array.from({length: 34}).map((_,i)=>(<rect key={i} x={70 + i*4} y="126" width={(i%3?1.4:2.6)} height="22" fill="var(--text-2)" />))}
              </g>
              {/* meter number highlighted */}
              <rect x="58" y="158" width="164" height="26" rx="7" fill="none" stroke="var(--accent)" strokeWidth="2.5" />
              <text x="140" y="175" fontFamily="var(--font-mono)" fontSize="13" fontWeight="600" fill="var(--text)" textAnchor="middle">1 ESY 0123 4567</text>
              {/* callout */}
              <path d="M222 171 H252 V120" stroke="var(--accent)" strokeWidth="2" fill="none" strokeLinecap="round" />
              <circle cx="252" cy="116" r="4" fill="var(--accent)" />
            </svg>
            <span className="pm-help-tag">Ihre Zählernummer</span>
          </div>
          <div className="pm-help-text">
            <p>Die <strong>Zählernummer</strong> steht direkt auf Ihrem Stromzähler — meist als längere Zahl <strong>unter dem Strichcode</strong>. Sie beginnt häufig mit einem Buchstaben­kürzel (z.&nbsp;B. <span className="mono">1&nbsp;ESY&nbsp;…</span>).</p>
            <ul className="pm-help-list">
              <li><I.check size={15} /> Nicht zu verwechseln mit dem <em>Zählerstand</em> (die kWh-Anzeige oben).</li>
              <li><I.check size={15} /> Bei modernen Zählern oft zusätzlich als QR- oder Strichcode aufgedruckt.</li>
              <li><I.check size={15} /> Den Zähler finden Sie meist im Keller, Hausanschlussraum oder Flur.</li>
            </ul>
            <div className="pm-help-hint"><I.camera size={16} /> Kein Zähler in der Nähe? Laden Sie einfach ein Foto hoch — wir übernehmen die Zuordnung.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EnergyFlowIllustration, ProcessSequence, SavingsComparison, MeterNumberHelpModal });
