// Shared UI components for TI_StockConnect

const { useState, useEffect, useMemo, useRef } = React;

// =============== Icons ===============
const Icon = {
  search: (
    <svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
  ),
  download: (
    <svg viewBox="0 0 24 24"><path d="M12 4v12"/><path d="m7 11 5 5 5-5"/><path d="M5 20h14"/></svg>
  ),
  plus: (
    <svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
  ),
  filter: (
    <svg viewBox="0 0 24 24"><path d="M3 5h18l-7 9v6l-4-2v-4z"/></svg>
  ),
  ext: (
    <svg viewBox="0 0 24 24"><path d="M14 4h6v6"/><path d="M10 14 20 4"/><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/></svg>
  ),
  settings: (
    <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3h0a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8v0a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>
  ),
  shield: (
    <svg viewBox="0 0 24 24"><path d="M12 2 4 5v6c0 5 3.5 9 8 11 4.5-2 8-6 8-11V5z"/></svg>
  ),
  users: (
    <svg viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.9"/><path d="M16 3.1a4 4 0 0 1 0 7.8"/></svg>
  ),
  edit: (
    <svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4z"/></svg>
  ),
  trash: (
    <svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
  ),
  copy: (
    <svg viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
  ),
  refresh: (
    <svg viewBox="0 0 24 24"><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></svg>
  ),
  alert: (
    <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
  ),
  check: (
    <svg viewBox="0 0 24 24"><path d="m5 12 5 5L20 7"/></svg>
  ),
  api: (
    <svg viewBox="0 0 24 24"><path d="M14 5h6v6"/><path d="m13 11 7-6"/><path d="M10 19H4v-6"/><path d="m11 13-7 6"/></svg>
  ),
  arrowUp: (<svg viewBox="0 0 24 24"><path d="m6 14 6-6 6 6"/></svg>),
  arrowDown: (<svg viewBox="0 0 24 24"><path d="m6 10 6 6 6-6"/></svg>),
  user: (<svg viewBox="0 0 24 24"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>),
  box: (<svg viewBox="0 0 24 24"><path d="M21 8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>),
  activity: (<svg viewBox="0 0 24 24"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>),
  trend: (<svg viewBox="0 0 24 24"><path d="M23 6l-9.5 9.5-5-5L1 18"/><path d="M17 6h6v6"/></svg>),
  globe: (<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>),
};

// =============== Language Selector ===============
function LanguageSelector() {
  const [open, setOpen] = useState(false);
  const [currentLang, setCurrentLang] = useState(getLanguage());
  const ref = useRef(null);

  useEffect(() => {
    const handleLangChange = (e) => setCurrentLang(e.detail);
    window.addEventListener('languageChange', handleLangChange);
    return () => window.removeEventListener('languageChange', handleLangChange);
  }, []);

  useEffect(() => {
    const handleClickOutside = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSelect = (lang) => {
    setLanguage(lang);
    setOpen(false);
  };

  const languages = getAvailableLanguages();
  const current = languages[currentLang];

  return (
    <div className="lang-selector" ref={ref}>
      <button className="lang-btn" onClick={() => setOpen(!open)} title="Lingua / Sprache / Langue / Lingua">
        <span className="lang-icon">{Icon.globe}</span>
        <span className="lang-code">{current.flag}</span>
      </button>
      {open && (
        <div className="lang-dropdown">
          {Object.values(languages).map(lang => (
            <button
              key={lang.code}
              className={"lang-option" + (lang.code === currentLang ? " active" : "")}
              onClick={() => handleSelect(lang.code)}
            >
              <span className="lang-option-flag">{lang.flag}</span>
              <span className="lang-option-name">{lang.name}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// =============== Header ===============
function AppHeader({ tenant, user, role, onRoleChange, viewingC2, config }) {
  return (
    <header className="app-header">
      <div className="app-header-inner">
        <div className="brand-left">
          <div className="producer-product">
            <div className="ti-logo-wrap">
              <img src="ti_logo.png" alt="Team Informatica" className="ti-logo-img" />
              <span className="ti-version">v 1.0.3</span>
            </div>
            <div className="product">
              <div className="product-mark"></div>
              <span className="product-name">TI_StockConnect</span>
            </div>
          </div>
        </div>
        <div className="brand-center">
          {config?.client_logo ? (
            <img src={config.client_logo} alt="Logo" className="client-logo-img" />
          ) : (
            <div className="client-logo-placeholder">
              <span>{config?.client_name || "Cliente"}</span>
            </div>
          )}
        </div>
        <div className="brand-right">
          <LanguageSelector />
          <div className="user-chip">
            <div className="user-avatar">{user?.initials || "U"}</div>
            <div className="user-meta">
              <div className="name">{user?.name || "Utente"}</div>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}

// =============== Top Nav ===============
function TopNav({ items, active, onSelect, onLogout }) {
  return (
    <nav className="top-nav">
      <div className="top-nav-inner">
        {items.map(item => (
          <button key={item.id}
            className={"nav-item" + (active === item.id ? " active" : "")}
            onClick={() => onSelect(item.id)}>
            {item.label}
          </button>
        ))}
        <div className="nav-spacer"></div>
        <button className="nav-exit" onClick={onLogout}>{t('logout')}</button>
      </div>
    </nav>
  );
}

// =============== Section header ===============
function SectionH({ children, sub }) {
  return <h2 className="section-h">{children}{sub && <span className="sub">{sub}</span>}</h2>;
}

// =============== Toggle ===============
function Toggle({ checked, onChange, label }) {
  return (
    <label className="toggle">
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
      <span className="switch"></span>
      {label && <span className="toggle-label">{label}</span>}
    </label>
  );
}

function Checkbox({ checked, onChange, label }) {
  return (
    <label className="checkbox">
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
      <span className="box"></span>
      {label}
    </label>
  );
}

// =============== Modal ===============
function Modal({ title, onClose, children, footer, size }) {
  const mouseDownTarget = useRef(null);
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  const handleMouseDown = (e) => {
    mouseDownTarget.current = e.target;
  };
  const handleMouseUp = (e) => {
    if (e.target === e.currentTarget && mouseDownTarget.current === e.currentTarget) {
      onClose();
    }
    mouseDownTarget.current = null;
  };
  return (
    <div className="modal-backdrop" onMouseDown={handleMouseDown} onMouseUp={handleMouseUp}>
      <div className={"modal" + (size === "lg" ? " modal-lg" : " modal-md")} onMouseDown={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>{title}</h2>
          <button className="close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-footer">{footer}</div>}
      </div>
    </div>
  );
}

// =============== Pagination ===============
function Pagination({ page, totalPages, onChange, total, totalLabel }) {
  const pages = [];
  const maxBtns = 7;
  let start = Math.max(1, page - 3);
  let end = Math.min(totalPages, start + maxBtns - 1);
  start = Math.max(1, end - maxBtns + 1);
  for (let i = start; i <= end; i++) pages.push(i);
  return (
    <div className="pagination">
      <div className="pages">
        <button onClick={() => onChange(Math.max(1, page - 1))}>‹</button>
        {pages.map(p => (
          <button key={p} className={p === page ? "active" : ""} onClick={() => onChange(p)}>{p}</button>
        ))}
        <button onClick={() => onChange(Math.min(totalPages, page + 1))}>›</button>
        <button onClick={() => onChange(totalPages)}>»</button>
      </div>
      {total !== undefined && (
        <div className="total">
          <span className="label">{totalLabel || "Totale"}</span>
          <span className="value">{total.toLocaleString("it-CH")}</span>
        </div>
      )}
    </div>
  );
}

// =============== Badge ===============
function Badge({ type = "neutral", children, dot }) {
  return <span className={"badge " + type}>{dot && <span className="dot"></span>}{children}</span>;
}

// =============== Sparkline ===============
function Sparkline({ values, color = "var(--ti-blue)" }) {
  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => `${(i / (values.length - 1)) * 100},${30 - ((v - min) / range) * 26 - 2}`).join(" ");
  return (
    <div className="spark">
      <svg viewBox="0 0 100 30" preserveAspectRatio="none">
        <polyline points={pts} fill="none" stroke={color} strokeWidth="1.4"/>
        <polyline points={`0,30 ${pts} 100,30`} fill={color} fillOpacity="0.12" stroke="none"/>
      </svg>
    </div>
  );
}

Object.assign(window, {
  Icon, AppHeader, TopNav, SectionH, Toggle, Checkbox, Modal, Pagination, Badge, Sparkline,
});
