import { useEffect, useMemo, useState } from 'react';
import FeatureCard from './FeatureCard';

const data = window.wowextHome || {};
const S = data.strings || {};

function GearIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
      <path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z" />
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 8 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 8a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 8 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V8c.26.604.97 1 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z" />
    </svg>
  );
}

const FILTERS = [
  { id: 'all', labelKey: 'filterAll' },
  { id: 'active', labelKey: 'filterActive' },
  { id: 'inactive', labelKey: 'filterInactive' },
  { id: 'addons', labelKey: 'filterAddons' },
  { id: 'core', labelKey: 'filterCore' },
];

export default function App() {
  const [extensions, setExtensions] = useState(data.extensions || []);
  const [filter, setFilter] = useState('all');
  const [notice, setNotice] = useState(null);

  useEffect(() => {
    if (!notice) return undefined;
    const t = setTimeout(() => setNotice(null), 8000);
    return () => clearTimeout(t);
  }, [notice]);

  function pushNotice(message, type) {
    if (!message) return;
    setNotice({ message, type: type === 'error' ? 'error' : 'success' });
  }

  const counts = useMemo(() => {
    const list = extensions;
    return {
      all: list.length,
      active: list.filter((e) => e.status === 'active').length,
      inactive: list.filter((e) => e.status === 'inactive').length,
      addons: list.filter((e) => !e.builtIn).length,
      core: list.filter((e) => e.builtIn).length,
    };
  }, [extensions]);

  const visible = useMemo(() => {
    return extensions.filter((ext) => {
      if (filter === 'all') return true;
      if (filter === 'active') return ext.status === 'active';
      if (filter === 'inactive') return ext.status === 'inactive';
      if (filter === 'addons') return !ext.builtIn;
      if (filter === 'core') return ext.builtIn;
      return true;
    });
  }, [extensions, filter]);

  function handleStatusChange(slug, newStatus) {
    setExtensions((prev) => {
      const next = prev.map((ext) => (ext.slug === slug ? { ...ext, status: newStatus } : ext));
      /** Keep localized bootstrap in sync so SPA remount (Home cache) sees current status. */
      if (typeof window.wowextHome !== 'undefined') {
        window.wowextHome.extensions = next;
      }
      if (typeof window.wowextWarmSettingsSurfaceCache === 'function') {
        window.wowextWarmSettingsSurfaceCache().catch(() => {});
      }
      return next;
    });
  }

  const settingsPageUrl = data.settingsPageUrl || '#';

  return (
    <div className="wowext-home-app">
      {notice && (
        <div
          className={`wowext-home-notice wowext-home-notice--${notice.type}`}
          role="alert"
        >
          <p className="wowext-home-notice__text">{notice.message}</p>
          <button
            type="button"
            className="wowext-home-notice__dismiss"
            onClick={() => setNotice(null)}
            aria-label={S.noticeDismiss || 'Dismiss notice'}
          >
            ×
          </button>
        </div>
      )}
      <div className="wowext-home-hero">
        <h1 className="wowext-home-hero__title">{S.heroTitle || "Let's start building."}</h1>
        <div className="wowext-home-toolbar">
          <div className="wowext-home-filters" role="tablist" aria-label="Filter extensions">
            {FILTERS.map((f) => {
              const n = counts[f.id] ?? 0;
              const label = S[f.labelKey] || f.id;
              const isActive = filter === f.id;
              return (
                <button
                  key={f.id}
                  type="button"
                  role="tab"
                  aria-selected={isActive}
                  className={`wowext-home-filter${isActive ? ' is-active' : ''}`}
                  onClick={() => setFilter(f.id)}
                >
                  {label} ({n})
                </button>
              );
            })}
          </div>
          <div className="wowext-home-tools">
            <a className="wowext-home-tool-btn" href={settingsPageUrl}>
              <GearIcon />
              <span>{S.toolManager || 'Extension settings'}</span>
            </a>
          </div>
        </div>
      </div>

      <div className="wowext-grid">
        {visible.map((ext) => (
          <FeatureCard
            key={ext.slug}
            extension={ext}
            onStatusChange={handleStatusChange}
            onNotify={pushNotice}
          />
        ))}
      </div>

      {visible.length === 0 && (
        <p className="wowext-home-empty">No extensions match this filter.</p>
      )}
    </div>
  );
}
