(function attachFreeSeoAgencyRecipesView(global) {
  const React = global.React;
  if (!React) return;

  function downloadBlob(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  }

  function FreeSeoAgencyRecipesView() {
    const [templates, setTemplates] = React.useState([]);
    const [stepTypes, setStepTypes] = React.useState([]);
    const [recipes, setRecipes] = React.useState([]);
    const [activeRecipe, setActiveRecipe] = React.useState(null);
    const [selectedTemplate, setSelectedTemplate] = React.useState(null);
    const [activeRun, setActiveRun] = React.useState(null);
    const [runWebsiteUrl, setRunWebsiteUrl] = React.useState('');
    const [error, setError] = React.useState('');

    React.useEffect(() => { loadInitial(); }, []);

    async function loadInitial() {
      try {
        const templateResponse = await global.JS_API.freeSeo.agencyRecipes.templates();
        const templateData = templateResponse.data || templateResponse;
        setTemplates(templateData.templates || []);
        setStepTypes(templateData.stepTypes || []);
        await refreshRecipes();
      } catch (err) { setError(err.message || 'Unable to load agency recipes.'); }
    }

    async function refreshRecipes() {
      const response = await global.JS_API.freeSeo.agencyRecipes.list({ limit: 50 });
      const data = response.data || response;
      setRecipes(data.items || []);
    }

    async function selectRecipe(recipe) {
      try {
        const response = await global.JS_API.freeSeo.agencyRecipes.get(recipe.id);
        setActiveRecipe(response.data || response);
        setSelectedTemplate(null);
        setActiveRun(null);
      } catch (err) { setError(err.message || 'Unable to load recipe.'); }
    }

    async function runRecipe(recipe) {
      try {
        const response = await global.JS_API.freeSeo.agencyRecipes.run(recipe.id, { mode: 'mixed', websiteUrl: runWebsiteUrl, variables: { websiteUrl: runWebsiteUrl } });
        const data = response.data || response;
        setActiveRecipe(data.recipe);
        setActiveRun(data.run);
        await refreshRecipes();
      } catch (err) { setError(err.message || 'Unable to run recipe.'); }
    }

    async function deleteRecipe(recipe) {
      if (!confirm(`Delete recipe "${recipe.name}"?`)) return;
      try { await global.JS_API.freeSeo.agencyRecipes.remove(recipe.id); if (activeRecipe && activeRecipe.id === recipe.id) setActiveRecipe(null); await refreshRecipes(); }
      catch (err) { setError(err.message || 'Unable to delete recipe.'); }
    }

    async function exportRun(format) {
      if (!activeRun) return;
      const blob = await global.JS_API.freeSeo.agencyRecipes.exportRun(activeRun.id, format);
      downloadBlob(blob, `${activeRun.id}-agency-recipe.${format === 'zip' ? 'zip' : format}`);
    }

    return <main className="free-seo-lab-view">
      <header className="page-header"><p className="eyebrow">Free SEO Lab</p><h1>Agency Recipes</h1><p className="muted">Reusable SEO/GEO workflow recipes for agency delivery, client onboarding, prospect packs, and recurring monitoring.</p></header>
      {error ? <div className="alert alert-error">{error}</div> : null}
      <div className="free-seo-card"><label>Run website URL<input value={runWebsiteUrl} onChange={(e) => setRunWebsiteUrl(e.target.value)} placeholder="https://client.example" /></label></div>
      <global.RecipeTemplateGallery templates={templates} onSelect={(template) => { setSelectedTemplate(template); setActiveRecipe(null); setActiveRun(null); }} />
      <div className="grid two align-start">
        <global.RecipeList recipes={recipes} activeRecipe={activeRecipe} onSelect={selectRecipe} onRun={runRecipe} onDelete={deleteRecipe} />
        <global.RecipeBuilder template={selectedTemplate} activeRecipe={activeRecipe} stepTypes={stepTypes} onSaved={(recipe) => { setActiveRecipe(recipe); setSelectedTemplate(null); refreshRecipes(); }} />
      </div>
      <global.RecipeRunTimeline run={activeRun} onExport={exportRun} />
    </main>;
  }

  global.FreeSeoAgencyRecipesView = FreeSeoAgencyRecipesView;
})(window);
