/* Powermieter — shared UI primitives (global). */
const { useRef: _useRef, useState: _useState, useEffect: _useEffect } = React;

function Logo({ size = 32 }) {
  /* Prefers the brand asset assets/logo.svg (drop in the real Powerhouse 360
     logo there); falls back to a theme-adaptive wordmark if it is missing. */
  const [imgOk, setImgOk] = _useState(true);
  if (imgOk) {
    return <img src="assets/logo.svg" alt="Powerhouse 360" style={{ height: size, display: 'block' }}
                onError={() => setImgOk(false)} />;
  }
  const m = Math.round(size * 0.92);
  return (
    <span className="pm-logo">
      <span className="pm-logo-mark" style={{ width: m, height: m, fontSize: m * 0.6 }}>
        <I.bolt size={Math.round(m * 0.56)} sw={2} />
      </span>
      <span className="pm-logo-word">Powerhouse<b>&nbsp;360</b></span>
    </span>
  );
}

const STEPS = ['Interesse', 'Daten', 'SEPA-Mandat', 'Vertrag'];

function ProcessNav({ current, maxReached = 1, onJump }) {
  return (
    <div className="pm-procnav">
      {STEPS.map((label, i) => {
        const n = i + 1;
        const done = n < current, active = n === current;
        const clickable = onJump && n <= maxReached && n !== current;
        return (
          <div key={n}
               className={`pm-procnav-step ${done ? 'is-done' : ''} ${active ? 'is-active' : ''} ${clickable ? 'is-clickable' : ''}`}
               onClick={clickable ? () => onJump(n) : undefined}>
            <span className="pm-procnav-dot">{done ? <I.checkSm size={15} /> : n}</span>
            <span className="pm-procnav-label">{label}</span>
            {n < STEPS.length && <span className="pm-procnav-bar" />}
          </div>
        );
      })}
    </div>
  );
}

function Field({ label, name, value, onChange, error, type = 'text', placeholder, optional, hint, inputMode, autoComplete, col2 }) {
  return (
    <label className={`pm-field ${col2 ? 'pm-col-2' : ''}`}>
      <span className="pm-label">{label}{optional && <span className="pm-opt"> · optional</span>}</span>
      <input className={`pm-input ${error ? 'is-error' : ''}`} type={type} value={value || ''}
        placeholder={placeholder} inputMode={inputMode} autoComplete={autoComplete}
        onChange={(e) => onChange(name, e.target.value)} />
      {error ? <span className="pm-err">{error}</span> : (hint && <span className="pm-hint">{hint}</span>)}
    </label>
  );
}

function Select({ label, name, value, onChange, options, error, optional, col2 }) {
  return (
    <label className={`pm-field ${col2 ? 'pm-col-2' : ''}`}>
      <span className="pm-label">{label}{optional && <span className="pm-opt"> · optional</span>}</span>
      <select className={`pm-select ${error ? 'is-error' : ''}`} value={value || ''} onChange={(e) => onChange(name, e.target.value)}>
        <option value="" disabled>Bitte wählen…</option>
        {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      {error && <span className="pm-err">{error}</span>}
    </label>
  );
}

function Consent({ name, checked, onChange, error, children }) {
  return (
    <label className={`pm-check ${error ? 'is-error' : ''}`}>
      <input type="checkbox" checked={!!checked} onChange={(e) => onChange(name, e.target.checked)} />
      <span className="pm-check-box"><I.checkSm size={14} /></span>
      <span className="pm-check-text">{children}</span>
    </label>
  );
}

function Button({ kind = 'primary', lg, block, busy, children, ...rest }) {
  return (
    <button className={`pm-btn pm-btn-${kind} ${lg ? 'pm-btn-lg' : ''} ${block ? 'pm-btn-block' : ''}`} {...rest}>
      {busy && <span className="pm-spin" />}{children}
    </button>
  );
}

function Note({ children }) {
  return <div className="pm-note"><I.info size={17} /><span>{children}</span></div>;
}

/* ---- Meter-reading photo (camera on mobile, downscaled client-side) ---- */
function PhotoCapture({ value, onChange, error }) {
  const inputRef = _useRef(null);
  const onFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const img = new Image();
      img.onload = () => {
        const max = 1280; let { width, height } = img;
        if (width > max || height > max) { const r = Math.min(max / width, max / height); width = Math.round(width * r); height = Math.round(height * r); }
        const c = document.createElement('canvas'); c.width = width; c.height = height;
        c.getContext('2d').drawImage(img, 0, 0, width, height);
        onChange(c.toDataURL('image/jpeg', 0.7));
      };
      img.src = reader.result;
    };
    reader.readAsDataURL(file);
  };
  return (
    <div className={`pm-photo ${error ? 'is-error' : ''}`}>
      <input ref={inputRef} type="file" accept="image/*" capture="environment" style={{ display: 'none' }} onChange={onFile} />
      {value ? (
        <div className="pm-photo-has">
          <img src={value} alt="Zählerstand" className="pm-photo-thumb" />
          <div className="pm-photo-actions">
            <span className="pm-trust"><I.checkSm size={14} style={{ color: 'var(--positive)' }} /> Foto erfasst</span>
            <button type="button" className="pm-sign-clear" onClick={() => onChange('')}><I.trash size={14} /> Entfernen</button>
          </div>
        </div>
      ) : (
        <button type="button" className="pm-photo-btn" onClick={() => inputRef.current && inputRef.current.click()}>
          <I.camera size={22} /><span>Foto vom Zählerstand aufnehmen</span><span className="pm-photo-sub">Kamera öffnen oder Bild wählen</span>
        </button>
      )}
      {error && <span className="pm-err">{error}</span>}
    </div>
  );
}

/* ---- Signature pad (built-in SES; mouse + touch) ---- */
function SignaturePad({ onChange, error }) {
  const canvasRef = _useRef(null);
  const [signed, setSigned] = _useState(false);
  const drawing = _useRef(false);
  const hasDrawn = _useRef(false);
  const last = _useRef(null);

  _useEffect(() => {
    const c = canvasRef.current;
    const ratio = window.devicePixelRatio || 1;
    const resize = () => {
      const r = c.getBoundingClientRect();
      c.width = r.width * ratio; c.height = r.height * ratio;
      const ctx = c.getContext('2d');
      ctx.scale(ratio, ratio);
      ctx.lineWidth = 2.2; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
      ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue('--text').trim() || '#0F1A2E';
    };
    resize();
    window.addEventListener('resize', resize);
    return () => window.removeEventListener('resize', resize);
  }, []);

  const pos = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    const t = e.touches ? e.touches[0] : e;
    return { x: t.clientX - r.left, y: t.clientY - r.top };
  };
  const start = (e) => { e.preventDefault(); drawing.current = true; last.current = pos(e); };
  const move = (e) => {
    if (!drawing.current) return; e.preventDefault();
    const ctx = canvasRef.current.getContext('2d'); const p = pos(e);
    ctx.beginPath(); ctx.moveTo(last.current.x, last.current.y); ctx.lineTo(p.x, p.y); ctx.stroke();
    last.current = p; hasDrawn.current = true; if (!signed) setSigned(true);
  };
  const end = () => { if (!drawing.current) return; drawing.current = false; if (hasDrawn.current) onChange(canvasRef.current.toDataURL('image/png')); };
  const clear = () => { const c = canvasRef.current; c.getContext('2d').clearRect(0, 0, c.width, c.height); hasDrawn.current = false; setSigned(false); onChange(''); };

  return (
    <div>
      <div className={`pm-sign ${signed ? 'is-signed' : ''} ${error ? 'is-error' : ''}`}>
        <canvas ref={canvasRef}
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end} />
        <div className="pm-sign-base" /><div className="pm-sign-x">✕</div>
        <div className="pm-sign-ph">Hier mit dem Finger oder der Maus unterschreiben</div>
      </div>
      <div className="pm-sign-actions">
        <span>{signed ? 'Unterschrift erfasst' : 'Rechtsgültige elektronische Unterschrift'}</span>
        {signed && <button type="button" className="pm-sign-clear" onClick={clear}>Neu unterschreiben</button>}
      </div>
      {error && <span className="pm-err">{error}</span>}
    </div>
  );
}

window.Logo = Logo; window.ProcessNav = ProcessNav; window.Field = Field; window.Select = Select;
window.Consent = Consent; window.Button = Button; window.Note = Note;
window.PhotoCapture = PhotoCapture; window.SignaturePad = SignaturePad;
