// Shared primitives for the Prophecta mining overview demo.
const { useCallback, useEffect, useMemo, useRef, useState } = React;

function BrandLogo({ height = 18 }) {
  const [theme, setTheme] = useState(() => document.documentElement.getAttribute('data-theme') || 'light');

  useEffect(() => {
    const observer = new MutationObserver(() => {
      setTheme(document.documentElement.getAttribute('data-theme') || 'light');
    });
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
    return () => observer.disconnect();
  }, []);

  const src = theme === 'dark' ? 'assets/prophecta-logo-dark.svg' : 'assets/prophecta-logo-light.svg';
  return <img src={src} alt="Prophecta" className="brand-logo" style={{ height }} />;
}

function Chip({ children }) {
  return (
    <span className="pa-chip">
      <span className="pa-chip-dot" />
      {children}
    </span>
  );
}

function ThemeToggle({ theme, onToggle }) {
  return (
    <button className="theme-toggle" type="button" onClick={onToggle} title="Toggle theme">
      <span className="theme-dot" aria-hidden="true" />
      <span>{theme === 'dark' ? 'dark' : 'light'}</span>
    </button>
  );
}

function SectionHeader({ eyebrow, titleId, title, kicker }) {
  return (
    <div className="section-header">
      <div>
        <span className="pa-eyebrow">{eyebrow}</span>
        <h2 className="section-title" id={titleId}>{title}</h2>
      </div>
      {kicker && <p className="section-kicker">{kicker}</p>}
    </div>
  );
}

function CopyPathButton({ value, onCopy }) {
  const [label, setLabel] = useState('Copy path');
  const [disabled, setDisabled] = useState(false);

  const handleClick = useCallback(async () => {
    setDisabled(true);
    setLabel('Copying...');
    const ok = await onCopy(value);
    setLabel(ok ? 'Copied' : 'Copy manually');
    window.setTimeout(() => {
      setDisabled(false);
      setLabel('Copy path');
    }, 1600);
  }, [onCopy, value]);

  return (
    <button className="copy-path" type="button" data-copy={value} disabled={disabled} onClick={handleClick}>
      {label}
    </button>
  );
}

function Toast({ message, visible }) {
  return (
    <div className={visible ? 'toast show' : 'toast'} role="status" aria-live="polite">
      {message || 'Copied'}
    </div>
  );
}

Object.assign(window, { BrandLogo, Chip, ThemeToggle, SectionHeader, CopyPathButton, Toast });
