/* Atoms: Button, Pill, Field, Input, Textarea, Checkbox, SectionEyebrow,
   IconCircle, EmojiContact, ChoiceChip, Card, Bullet */

const dsButton = ({ variant = 'primary', children, onClick, type = 'button', size = 'md', icon = null, style = {} }) => {
  const sizes = {
    sm: { padding: '9px 16px', fontSize: 13 },
    md: { padding: '13px 24px', fontSize: 15 },
    lg: { padding: '16px 30px', fontSize: 17 },
  };
  const variants = {
    primary: {
      background: 'var(--brand-coral-500)',
      color: '#fff',
      border: '1px solid transparent',
      boxShadow: '0 2px 6px rgba(241,95,87,0.28)',
    },
    secondary: {
      background: 'transparent',
      color: 'var(--brand-blue-700)',
      border: '1px solid var(--brand-blue-700)',
    },
    ghost: {
      background: 'transparent',
      color: 'var(--brand-blue-700)',
      border: '1px solid transparent',
      padding: '8px 4px',
    },
    inverse: {
      background: '#fff',
      color: 'var(--brand-blue-700)',
      border: '1px solid transparent',
      boxShadow: '0 6px 16px rgba(0,0,0,0.18)',
    },
    inverseOutline: {
      background: 'transparent',
      color: '#fff',
      border: '1px solid rgba(255,255,255,0.55)',
    },
  };
  const [hover, setHover] = React.useState(false);
  const hoverStyles = {
    primary: hover ? { background: 'var(--brand-coral-600)', transform: 'translateY(-1px)', boxShadow: '0 8px 22px rgba(241,95,87,0.35)' } : null,
    secondary: hover ? { background: 'var(--brand-blue-700)', color: '#fff' } : null,
    ghost: hover ? { color: 'var(--brand-coral-500)' } : null,
    inverse: hover ? { transform: 'translateY(-1px)', boxShadow: '0 10px 24px rgba(0,0,0,0.22)' } : null,
    inverseOutline: hover ? { background: 'rgba(255,255,255,0.10)', borderColor: '#fff' } : null,
  };
  return (
    <button
      type={type}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        fontFamily: 'var(--font-sans)',
        fontWeight: 600,
        lineHeight: 1,
        borderRadius: 999,
        cursor: 'pointer',
        display: 'inline-flex',
        alignItems: 'center',
        gap: 10,
        transition: 'all 160ms cubic-bezier(.2,.7,.2,1)',
        textDecoration: hover && variant === 'ghost' ? 'underline' : 'none',
        ...sizes[size],
        ...variants[variant],
        ...hoverStyles[variant],
        ...style,
      }}
    >
      {children}
      {icon === 'arrow' && <span style={{ fontSize: '1.1em' }}>→</span>}
      {icon === 'download' && <span style={{ fontSize: '1.1em' }}>↓</span>}
    </button>
  );
};

const dsPill = ({ children, tone = 'neutral', style = {} }) => {
  const tones = {
    neutral: { bg: 'var(--ink-100)', fg: 'var(--fg-2)' },
    coral: { bg: 'rgba(241,95,87,0.14)', fg: 'var(--brand-coral-600)' },
    cyan: { bg: 'rgba(0,172,212,0.16)', fg: '#006e87' },
    blue: { bg: 'var(--brand-blue-700)', fg: '#fff' },
    outline: { bg: 'transparent', fg: 'var(--fg-2)', border: '1px solid var(--border-strong)' },
    invOutline: { bg: 'transparent', fg: '#fff', border: '1px solid rgba(255,255,255,0.36)' },
  };
  const t = tones[tone];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '6px 14px', borderRadius: 999,
      fontSize: 13, fontWeight: 600, lineHeight: 1.2,
      background: t.bg, color: t.fg,
      border: t.border || '1px solid transparent',
      ...style,
    }}>{children}</span>
  );
};

const dsField = ({ label, hint, error, children, optional }) => (
  <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', display: 'flex', alignItems: 'baseline', gap: 8 }}>
      {label}
      {optional && <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-3)' }}>· optional</span>}
    </span>
    {children}
    {error && <span style={{ fontSize: 13, color: 'var(--brand-coral-600)' }}>{error}</span>}
    {hint && !error && <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>{hint}</span>}
  </label>
);

const dsInput = (props) => {
  const [focus, setFocus] = React.useState(false);
  return (
    <input
      {...props}
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      style={{
        fontFamily: 'var(--font-sans)',
        fontSize: 15,
        padding: '11px 14px',
        borderRadius: 14,
        border: `1px solid ${focus ? 'var(--brand-cyan-400)' : 'var(--border-strong)'}`,
        boxShadow: focus ? '0 0 0 3px rgba(0,172,212,0.25)' : 'none',
        background: '#fff',
        color: 'var(--fg-1)',
        outline: 'none',
        transition: 'box-shadow 120ms, border 120ms',
        ...(props.style || {}),
      }}
    />
  );
};

const dsTextarea = (props) => {
  const [focus, setFocus] = React.useState(false);
  return (
    <textarea
      {...props}
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      style={{
        fontFamily: 'var(--font-sans)',
        fontSize: 15,
        padding: '11px 14px',
        borderRadius: 14,
        border: `1px solid ${focus ? 'var(--brand-cyan-400)' : 'var(--border-strong)'}`,
        boxShadow: focus ? '0 0 0 3px rgba(0,172,212,0.25)' : 'none',
        background: '#fff',
        color: 'var(--fg-1)',
        outline: 'none',
        resize: 'vertical',
        minHeight: 110,
        ...(props.style || {}),
      }}
    />
  );
};

const dsCheckbox = ({ checked, onChange, children }) => (
  <label style={{ display: 'flex', gap: 12, alignItems: 'flex-start', cursor: 'pointer', fontSize: 14, color: 'var(--fg-2)', lineHeight: 1.55 }}>
    <span
      onClick={() => onChange(!checked)}
      style={{
        width: 22, height: 22,
        border: '1.5px solid var(--brand-blue-700)',
        borderRadius: 6,
        flex: 'none',
        background: checked ? 'var(--brand-blue-700)' : 'transparent',
        display: 'grid', placeItems: 'center',
        marginTop: 1,
        transition: 'background 120ms',
      }}
    >
      {checked && <span style={{ color: '#fff', fontWeight: 800, fontSize: 13 }}>✓</span>}
    </span>
    <span>{children}</span>
  </label>
);

const dsSectionEyebrow = ({ children, tone = 'coral', style = {} }) => (
  <div style={{
    fontSize: 13, fontWeight: 600,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: tone === 'coral' ? 'var(--brand-coral-500)'
         : tone === 'cyan' ? 'var(--brand-cyan-400)'
         : tone === 'blue' ? 'var(--brand-blue-700)'
         : 'var(--fg-3)',
    ...style,
  }}>{children}</div>
);

const dsIconCircle = ({ children, color = 'coral', size = 40, style = {} }) => {
  const bgs = {
    coral: 'var(--brand-coral-500)',
    cyan: 'var(--brand-cyan-400)',
    blue: 'var(--brand-blue-700)',
    white: '#fff',
    cream: 'var(--cream)',
  };
  return (
    <span style={{
      width: size, height: size, borderRadius: 999,
      background: bgs[color],
      color: color === 'white' || color === 'cream' ? 'var(--brand-blue-700)' : '#fff',
      display: 'grid', placeItems: 'center',
      fontWeight: 800, fontSize: size * 0.42, flex: 'none',
      ...style,
    }}>{children}</span>
  );
};

/* ContactIcon — three monochrome line icons sharing the same visual
   language. 24×24 viewBox, 1.6 stroke, round caps/joins, currentColor,
   no fill. Pass kind="mail" | "phone" | "instagram". */
const ContactIcon = ({ kind, size = 20, style = {} }) => {
  const common = {
    width: size, height: size, viewBox: '0 0 24 24',
    fill: 'none', stroke: 'currentColor',
    strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round',
    style,
  };
  if (kind === 'mail') {
    return (
      <svg {...common} aria-hidden="true">
        <rect x="3" y="5.5" width="18" height="13" rx="2.4" />
        <path d="M3.6 7 11.2 12.7a1.4 1.4 0 0 0 1.6 0L20.4 7" />
      </svg>
    );
  }
  if (kind === 'phone') {
    return (
      <svg {...common} aria-hidden="true">
        <path d="M5.6 3.5h3l1.6 4-2.1 1.4a13 13 0 0 0 7 7l1.4-2.1 4 1.6v3a2 2 0 0 1-2.2 2A17 17 0 0 1 3.6 5.7a2 2 0 0 1 2-2.2Z" />
      </svg>
    );
  }
  if (kind === 'instagram') {
    return (
      <svg {...common} aria-hidden="true">
        <rect x="3.5" y="3.5" width="17" height="17" rx="4.5" />
        <circle cx="12" cy="12" r="4" />
        <circle cx="17.1" cy="6.9" r="0.9" fill="currentColor" stroke="none" />
      </svg>
    );
  }
  return null;
};

/* EmojiContact (kept name for compatibility) — accepts a `kind` prop
   ('mail' | 'phone' | 'instagram') and renders a matching line icon.
   The legacy `icon` prop still works for one-off emoji use. */
const dsEmojiContact = ({ icon, kind, children, dark = false, href, style = {} }) => {
  const inner = (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      fontSize: 16,
      color: dark ? '#fff' : 'var(--fg-1)',
      ...style,
    }}>
      {kind ? (
        <ContactIcon kind={kind} size={20} style={{
          color: dark ? 'var(--brand-cyan-400)' : 'var(--brand-blue-700)',
          flex: 'none',
        }} />
      ) : (
        <span style={{ fontSize: 18, lineHeight: 1 }}>{icon}</span>
      )}
      <span>{children}</span>
    </div>
  );
  if (href) {
    const isExternal = href.startsWith('http');
    return (
      <a href={href}
         style={{ textDecoration: 'none', color: 'inherit' }}
         {...(isExternal ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
        {inner}
      </a>
    );
  }
  return inner;
};

const dsChoiceChip = ({ selected, onClick, children }) => (
  <button type="button" onClick={onClick} style={{
    padding: '9px 16px', borderRadius: 999,
    fontSize: 13, fontWeight: 600, cursor: 'pointer',
    background: selected ? 'var(--brand-blue-700)' : 'transparent',
    color: selected ? '#fff' : 'var(--fg-2)',
    border: `1px solid ${selected ? 'var(--brand-blue-700)' : 'var(--border-strong)'}`,
    fontFamily: 'var(--font-sans)',
    transition: 'all 120ms cubic-bezier(.2,.7,.2,1)',
  }}>{children}</button>
);

const dsCard = ({ children, style = {}, tone = 'white' }) => {
  const bgs = {
    white: '#fff',
    cream: 'var(--cream)',
    warm: 'var(--off-white)',
  };
  return (
    <div style={{
      background: bgs[tone],
      borderRadius: 22,
      border: '1px solid var(--border-soft)',
      padding: 26,
      boxShadow: tone === 'white' ? '0 2px 6px rgba(14,42,56,0.06)' : 'none',
      ...style,
    }}>{children}</div>
  );
};

/* Bullet — replaces native list bullets with the cyan pointing-hand icon
   from the brand. Used in copy-heavy lists across the site. */
const dsBullet = ({ children, tone = 'cyan' }) => {
  const colors = {
    cyan: 'var(--brand-cyan-400)',
    coral: 'var(--brand-coral-500)',
    blue: 'var(--brand-blue-700)',
  };
  return (
    <li style={{ display: 'grid', gridTemplateColumns: '22px 1fr', gap: 14, alignItems: 'flex-start' }}>
      <span aria-hidden style={{
        width: 12, height: 12, borderRadius: 999,
        marginTop: 8, background: colors[tone],
        boxShadow: `0 0 0 4px ${tone === 'cyan' ? 'rgba(0,172,212,0.18)'
                                : tone === 'coral' ? 'rgba(241,95,87,0.18)'
                                : 'rgba(0,84,118,0.18)'}`,
      }}/>
      <span style={{ paddingTop: 1 }}>{children}</span>
    </li>
  );
};

/* Numbered step badge */
const dsNum = ({ n, tone = 'coral' }) => (
  <span style={{
    width: 36, height: 36, borderRadius: 999,
    background: tone === 'coral' ? 'rgba(241,95,87,0.16)'
              : tone === 'cyan'  ? 'rgba(0,172,212,0.18)'
              : 'rgba(0,84,118,0.12)',
    color:      tone === 'coral' ? 'var(--brand-coral-600)'
              : tone === 'cyan'  ? '#006e87'
              : 'var(--brand-blue-700)',
    display: 'grid', placeItems: 'center',
    fontWeight: 800, fontSize: 16, fontVariantNumeric: 'tabular-nums',
    flex: 'none',
  }}>{n}</span>
);

/* ---- useBreakpoint ---- */
const useBreakpoint = () => {
  const [width, setWidth] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const h = () => setWidth(window.innerWidth);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return {
    isMobile:  width < 768,
    isTablet:  width >= 768 && width < 1024,
    isDesktop: width >= 1024,
    width,
  };
};

/* ---- ImageLightbox ---- */
// images: [{src, alt}, ...] für Gallery-Modus. index + onNavigate optional.
const ImageLightbox = ({ src, alt, onClose, images, index, onNavigate }) => {
  const isGallery = images && images.length > 1;
  const current = (images && images.length > 0) ? images[index] : { src, alt };
  const prev = () => onNavigate((index - 1 + images.length) % images.length);
  const next = () => onNavigate((index + 1) % images.length);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (isGallery && e.key === 'ArrowLeft') prev();
      if (isGallery && e.key === 'ArrowRight') next();
    };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose, index, isGallery]);

  const navBtn = (onClick, label, side) => (
    <button
      onClick={(e) => { e.stopPropagation(); onClick(); }}
      aria-label={label}
      style={{
        position: 'fixed', top: '50%', transform: 'translateY(-50%)',
        [side]: 16,
        background: 'rgba(255,255,255,0.12)',
        border: '1px solid rgba(255,255,255,0.25)',
        borderRadius: '50%', width: 44, height: 44,
        color: '#fff', fontSize: 22, cursor: 'pointer',
        display: 'grid', placeItems: 'center',
        zIndex: 2001,
      }}
    >{label === 'Zurück' ? '‹' : '›'}</button>
  );

  return (
    <div
      role="dialog" aria-modal="true"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 2000,
        background: 'rgba(0,28,42,0.85)',
        backdropFilter: 'blur(6px)',
        WebkitBackdropFilter: 'blur(6px)',
        display: 'grid', placeItems: 'center',
        padding: 24,
        cursor: 'zoom-out',
      }}
    >
      <img
        src={current.src} alt={current.alt}
        onClick={(e) => e.stopPropagation()}
        style={{
          maxWidth: '90vw', maxHeight: '90vh',
          borderRadius: 16,
          boxShadow: '0 32px 80px rgba(0,0,0,0.6)',
          cursor: 'default',
        }}
      />
      <button
        onClick={onClose}
        style={{
          position: 'fixed', top: 20, right: 20,
          background: 'rgba(255,255,255,0.12)',
          border: '1px solid rgba(255,255,255,0.25)',
          borderRadius: '50%', width: 40, height: 40,
          color: '#fff', fontSize: 20, cursor: 'pointer',
          display: 'grid', placeItems: 'center',
          zIndex: 2001,
        }}
        aria-label="Schließen"
      >×</button>
      {isGallery && navBtn(prev, 'Zurück', 'left')}
      {isGallery && navBtn(next, 'Weiter', 'right')}
      {isGallery && (
        <div style={{
          position: 'fixed', bottom: 20, left: '50%', transform: 'translateX(-50%)',
          display: 'flex', gap: 8, zIndex: 2001,
        }}>
          {images.map((_, i) => (
            <button
              key={i}
              onClick={(e) => { e.stopPropagation(); onNavigate(i); }}
              style={{
                width: i === index ? 20 : 8, height: 8, borderRadius: 4,
                background: i === index ? '#fff' : 'rgba(255,255,255,0.4)',
                border: 'none', cursor: 'pointer', padding: 0,
                transition: 'all 200ms',
              }}
            />
          ))}
        </div>
      )}
    </div>
  );
};

Object.assign(window, {
  Button: dsButton,
  Pill: dsPill,
  Field: dsField,
  Input: dsInput,
  Textarea: dsTextarea,
  Checkbox: dsCheckbox,
  SectionEyebrow: dsSectionEyebrow,
  IconCircle: dsIconCircle,
  EmojiContact: dsEmojiContact,
  ContactIcon: ContactIcon,
  ChoiceChip: dsChoiceChip,
  Card: dsCard,
  Bullet: dsBullet,
  Num: dsNum,
  useBreakpoint,
  ImageLightbox,
});
