/* Powermieter — shared UI primitives. Exports to window. */
const { useState, useRef, useEffect, useId } = React;

/* ---------- Brand ---------- */
function Brandmark({ size = 34 }) {
  return (
    <span style={{
      width: size, height: size, flex: 'none', borderRadius: size * .28,
      background: 'linear-gradient(150deg, var(--navy-700), var(--navy-900))',
      display: 'grid', placeItems: 'center', position: 'relative', overflow: 'hidden',
      boxShadow: 'inset 0 0 0 1px #ffffff10, var(--shadow-sm)'
    }}>
      <span style={{ position: 'absolute', inset: 0, background: 'radial-gradient(60% 60% at 70% 20%, color-mix(in oklab, var(--accent-400) 55%, transparent), transparent 70%)' }} />
      <I.bolt size={size * .56} fill="var(--accent-400)" style={{ color: 'var(--accent-400)', position: 'relative' }} sw={0} />
    </span>
  );
}
function Logo({ size = 34, light }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
      <img src="assets/ph360-mark.png" alt="PowerHouse 360" style={{ height: size, width: 'auto', flex: 'none', display: 'block' }} />
      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: size * .44,
        letterSpacing: '-.01em', color: light ? '#fff' : 'var(--navy-700)', lineHeight: 1, whiteSpace: 'nowrap' }}>
        POWER<span style={{ fontWeight: 600, color: light ? '#C6D4E6' : 'var(--navy-500, var(--text-2))' }}>HOUSE</span>{' '}
        <span style={{ background: 'linear-gradient(90deg, var(--accent), var(--positive))', WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent', fontWeight: 800 }}>360</span>
      </span>
    </span>
  );
}

/* ---------- Button ---------- */
function Button({ variant = 'primary', size, block, icon, iconRight, className, children, onClick, type, disabled, style, title, id }) {
  const cls = ['btn', `btn-${variant}`, size && `btn-${size}`, block && 'btn-block', className].filter(Boolean).join(' ');
  return (
    <button className={cls} onClick={onClick} type={type} disabled={disabled} style={style} title={title} id={id}>
      {icon}{children}{iconRight}
    </button>
  );
}

/* ---------- Chip ---------- */
function Chip({ tone, icon, children }) {
  return <span className={`chip${tone ? ' chip-' + tone : ''}`}>{icon}{children}</span>;
}

/* ---------- Process navigation (the 4-step stepper) ---------- */
const STEPS = [
  { n: 1, label: 'Interesse',       short: 'Interesse',  icon: I.spark },
  { n: 2, label: 'Registrierung',   short: 'Daten',      icon: I.user },
  { n: 3, label: 'Vertragsabschluss',short: 'Vertrag',   icon: I.signature },
  { n: 4, label: 'Aktivierung',     short: 'Aktiv',      icon: I.checkBold },
];

function ProcessNav({ current, maxReached = current, onJump, compact }) {
  return (
    <nav className="pm-stepper" data-compact={compact ? 'true' : 'false'} aria-label="Fortschritt">
      {STEPS.map((s, i) => {
        const done = s.n < current;
        const active = s.n === current;
        const reachable = s.n <= maxReached;
        const Ic = s.icon;
        return (
          <React.Fragment key={s.n}>
            <button
              className="pm-step"
              data-state={active ? 'active' : done ? 'done' : 'todo'}
              data-reach={reachable ? 'y' : 'n'}
              onClick={() => reachable && onJump && onJump(s.n)}
              disabled={!reachable}
              aria-current={active ? 'step' : undefined}
            >
              <span className="pm-step-dot">
                {done ? <I.check size={16} /> : <Ic size={16} />}
              </span>
              <span className="pm-step-text">
                <span className="pm-step-n">Schritt {s.n}</span>
                <span className="pm-step-label">{compact ? s.short : s.label}</span>
              </span>
            </button>
            {i < STEPS.length - 1 && (
              <span className="pm-step-line" data-done={s.n < current ? 'true' : 'false'} aria-hidden="true">
                <span className="pm-step-line-fill" />
              </span>
            )}
          </React.Fragment>
        );
      })}
    </nav>
  );
}

/* ---------- Form field wrapper ---------- */
function Field({ label, required, optional, hint, error, htmlFor, tip, children }) {
  return (
    <div className="field">
      {label && (
        <label className="field-label" htmlFor={htmlFor}>
          {label}
          {required && <span className="field-req" title="Pflichtfeld">*</span>}
          {optional && <span className="field-opt">optional</span>}
          {tip && <Tooltip text={tip}><I.help size={15} /></Tooltip>}
        </label>
      )}
      {children}
      {error ? <span className="field-err"><I.alert size={14} />{error}</span>
             : hint ? <span className="field-hint">{hint}</span> : null}
    </div>
  );
}

function TextInput({ error, affix, ...rest }) {
  const cls = 'input' + (error ? ' input-err' : '');
  if (affix) return (
    <div className="input-wrap"><input className={cls} {...rest} /><span className="input-affix">{affix}</span></div>
  );
  return <input className={cls} {...rest} />;
}

function TextArea({ error, ...rest }) {
  return <textarea className={'textarea' + (error ? ' input-err' : '')} {...rest} />;
}

function Select({ error, children, ...rest }) {
  return (
    <div className="select-wrap">
      <select className={'select' + (error ? ' input-err' : '')} {...rest}>{children}</select>
      <I.chevDown size={18} className="select-caret" />
    </div>
  );
}

/* ---------- Checkbox ---------- */
function Checkbox({ checked, onChange, children }) {
  return (
    <label className="check" data-checked={checked ? 'true' : 'false'}>
      <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }} />
      <span className="check-box"><I.check sw={3} /></span>
      <span className="check-text">{children}</span>
    </label>
  );
}

/* ---------- Segmented ---------- */
function Segmented({ value, onChange, options }) {
  return (
    <div className="seg" role="tablist">
      {options.map(o => (
        <button key={o.value} className="seg-btn" data-on={value === o.value ? 'true' : 'false'}
          onClick={() => onChange(o.value)} role="tab" aria-selected={value === o.value}>
          {o.icon}{o.label}
        </button>
      ))}
    </div>
  );
}

/* ---------- Tooltip ---------- */
function Tooltip({ text, children }) {
  return (
    <span className="tip">
      <span className="tip-trigger" tabIndex={0}>{children}</span>
      <span className="tip-bubble" role="tooltip">{text}</span>
    </span>
  );
}

/* ---------- Alert ---------- */
function Alert({ tone = 'info', icon, children }) {
  const def = { info: I.info, positive: I.shield, warn: I.alert }[tone];
  const Ic = icon ? () => icon : def;
  return <div className={`alert alert-${tone}`}>{icon || <Ic size={18} />}<div>{children}</div></div>;
}

/* ---------- Accordion ---------- */
function AccordionItem({ q, defaultOpen, children }) {
  const [open, setOpen] = useState(!!defaultOpen);
  const ref = useRef(null);
  const [h, setH] = useState(defaultOpen ? 'auto' : 0);
  useEffect(() => {
    if (!ref.current) return;
    setH(open ? ref.current.scrollHeight : 0);
  }, [open]);
  return (
    <div className="acc-item">
      <button className="acc-head" data-open={open ? 'true' : 'false'} onClick={() => setOpen(o => !o)} aria-expanded={open}>
        <span>{q}</span><I.chevDown size={20} className="acc-icon" />
      </button>
      <div className="acc-panel" style={{ height: h }}>
        <div className="acc-body" ref={ref}>{children}</div>
      </div>
    </div>
  );
}
function Accordion({ children }) { return <div className="acc">{children}</div>; }

/* ---------- Stat ---------- */
function Stat({ value, label, tone, sub }) {
  return (
    <div className="pm-stat">
      <div className="pm-stat-value tnum" style={tone ? { color: `var(--${tone})` } : undefined}>{value}</div>
      <div className="pm-stat-label">{label}</div>
      {sub && <div className="pm-stat-sub">{sub}</div>}
    </div>
  );
}

/* ---------- Benefit card ---------- */
function BenefitCard({ icon, title, children }) {
  return (
    <div className="pm-benefit">
      <span className="pm-benefit-ic">{icon}</span>
      <div className="pm-benefit-title">{title}</div>
      <div className="pm-benefit-text">{children}</div>
    </div>
  );
}

/* ---------- Section header ---------- */
function FormSection({ step, title, desc, children }) {
  return (
    <section className="pm-fsec">
      <div className="pm-fsec-head">
        {step && <span className="pm-fsec-step">{step}</span>}
        <div>
          <h3 className="pm-fsec-title">{title}</h3>
          {desc && <p className="pm-fsec-desc">{desc}</p>}
        </div>
      </div>
      <div className="pm-fsec-body">{children}</div>
    </section>
  );
}

Object.assign(window, {
  Brandmark, Logo, Button, Chip, ProcessNav, STEPS, Field, TextInput, TextArea,
  Select, Checkbox, Segmented, Tooltip, Alert, Accordion, AccordionItem, Stat,
  BenefitCard, FormSection,
});
