/* Templates gallery — wired to live /api/templates.
   Returns { templates: [...] }. Each template has id, name, description,
   category/objective, mode, layout_id, blocks, accent_color,
   thumb_gradient, sort_order. */

function TPL_thumbBg(t) {
  if (t.thumb_gradient) return t.thumb_gradient;
  if (t.accent_color) {
    return `linear-gradient(135deg, ${t.accent_color}, color-mix(in srgb, ${t.accent_color} 35%, var(--aq-bg-2) 65%))`;
  }
  return 'linear-gradient(135deg, oklch(0.30 0.06 220), oklch(0.18 0.04 240))';
}

function TemplatesScreen() {
  const [templates, setTemplates] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [cat, setCat] = useState('all');

  useEffect(() => {
    let cancelled = false;
    apiFetch('/api/templates')
      .then((res) => {
        if (cancelled) return;
        setTemplates(res.templates || []);
        setLoading(false);
      })
      .catch((err) => {
        if (cancelled) return;
        setError(err.message);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, []);

  const cats = useMemo(() => {
    const set = new Set();
    templates.forEach((t) => {
      const c = t.category || t.objective || t.mode || 'other';
      set.add(c);
    });
    return [{ id: 'all', label: 'All' }, ...Array.from(set).map((c) => ({ id: c, label: c }))];
  }, [templates]);

  const filtered = useMemo(() => {
    if (cat === 'all') return templates;
    return templates.filter((t) => (t.category || t.objective || t.mode || 'other') === cat);
  }, [templates, cat]);

  return (
    <div className="aq-content">
      <div className="aq-content-inner" style={{ maxWidth: 1280 }}>
        <section className="x-tpl-hero" style={{ marginBottom: 18 }}>
          <div className="x-eyebrow">Templates</div>
          <h2>Start from a template</h2>
          <p>
            Pre-built creative formats designed for aquarium and visitor-attraction screens. Pick one to seed a new campaign.
          </p>
        </section>

        {loading && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--aq-text-faint)' }}>
            Loading templates…
          </div>
        )}
        {error && (
          <div style={{
            padding: '10px 14px',
            background: 'color-mix(in srgb, var(--aq-danger) 12%, transparent)',
            border: '1px solid color-mix(in srgb, var(--aq-danger) 30%, transparent)',
            borderRadius: 6, color: 'var(--aq-danger)', fontSize: 12,
          }}>{error}</div>
        )}

        {!loading && !error && (
          <>
            {cats.length > 1 && (
              <div className="x-tabs" style={{ marginBottom: 14 }}>
                {cats.map((t) => {
                  const count = t.id === 'all'
                    ? templates.length
                    : templates.filter((x) => (x.category || x.objective || x.mode || 'other') === t.id).length;
                  return (
                    <button
                      key={t.id}
                      className={`x-tab ${cat === t.id ? 'is-active' : ''}`}
                      onClick={() => setCat(t.id)}
                      style={{ textTransform: 'capitalize' }}
                    >
                      {t.label}
                      <span className="x-tab-count">{count}</span>
                    </button>
                  );
                })}
              </div>
            )}

            {filtered.length === 0 ? (
              <div className="x-card" style={{ padding: '60px 24px', textAlign: 'center' }}>
                <div style={{ fontSize: 13, color: 'var(--aq-text-faint)' }}>
                  No templates in this category.
                </div>
              </div>
            ) : (
              <div className="x-tpl-grid">
                {filtered.map((t) => (
                  <div
                    key={t.id}
                    className={`x-tpl-card ${t.is_featured ? 'is-featured' : ''}`}
                    onClick={async () => {
                      /* Use template — POST /api/campaigns/from-template/:tid
                         seeds a draft campaign with the template's layout
                         and accent. Backend authorize is org_admin / site_
                         manager / marketing_admin / aquaos_admin so this
                         silently no-ops for designers/operators. */
                      if (!Auth.canEditCampaigns()) {
                        window.alert('Templates can only be used by editors. Ask an admin to create one for you.');
                        return;
                      }
                      const name = window.prompt(`Name for new campaign:`, t.name);
                      if (!name) return;
                      try {
                        const created = await apiFetch(`/api/campaigns/from-template/${t.id}`, {
                          method: 'POST',
                          body: JSON.stringify({ name }),
                        });
                        if (created && created.id) {
                          window.location.hash = `#campaign-edit/${created.id}`;
                        }
                      } catch (err) {
                        window.alert(`Couldn't create from template: ${err.message}`);
                      }
                    }}
                    style={{ cursor: 'pointer' }}
                  >
                    <div className="x-tpl-thumb" style={{ background: TPL_thumbBg(t) }}>
                      {t.is_featured && <span className="x-tpl-thumb-tag is-featured">Featured</span>}
                      {!t.is_featured && t.layout_id && (
                        <span className="x-tpl-thumb-tag">{t.layout_id}</span>
                      )}
                    </div>
                    <div className="x-tpl-body">
                      <div className="x-tpl-name">{t.name}</div>
                      <div className="x-tpl-desc">{t.description || '—'}</div>
                      <div className="x-tpl-meta">
                        <span>{t.category || t.objective || t.mode || ''}</span>
                        <span>Use →</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

window.TemplatesScreen = TemplatesScreen;
