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

  function FreeSeoAiFindabilityView() {
    const [runs, setRuns] = React.useState([]);
    const [activeRun, setActiveRun] = React.useState(null);
    const [error, setError] = React.useState('');

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

    async function refreshRuns() {
      try {
        const response = await global.JS_API.freeSeo.aiFindability.listRuns({ limit: 20 });
        const data = response.data || response;
        setRuns(data.items || data || []);
      } catch (err) { setError(err.message || 'Unable to load AI findability runs.'); }
    }

    async function selectRun(run) {
      setActiveRun(run);
      try {
        const response = await global.JS_API.freeSeo.aiFindability.getRun(run.id);
        setActiveRun(response.data || response);
      } catch (err) { setError(err.message || 'Unable to load run.'); }
    }

    async function exportRun(format) {
      if (!activeRun) return;
      const blob = await global.JS_API.freeSeo.aiFindability.exportRun(activeRun.id, format);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${activeRun.id}-ai-findability.${format === 'zip' ? 'zip' : format}`;
      a.click();
      URL.revokeObjectURL(url);
    }

    return <main className="free-seo-lab-view">
      <header className="page-header"><p className="eyebrow">Free SEO Lab</p><h1>AI Findability</h1><p className="muted">Local readiness tests for AI-style service and location discovery questions.</p></header>
      {error ? <div className="alert alert-error">{error}</div> : null}
      <window.FindabilityRunForm onRunCreated={(run) => { setActiveRun(run); refreshRuns(); }} />
      <section className="free-seo-card"><h2>Recent runs</h2>{!runs.length ? <p className="muted">No runs yet.</p> : <ul className="run-list">{runs.map((run) => <li key={run.id}><button onClick={() => selectRun(run)}>{run.websiteUrl || run.id} - {run.summary && run.summary.grade || run.status}</button></li>)}</ul>}</section>
      {activeRun ? <><div className="row gap"><button className="button" onClick={() => exportRun('html')}>Export HTML</button><button className="button" onClick={() => exportRun('json')}>Export JSON</button><button className="button" onClick={() => exportRun('zip')}>Export ZIP</button></div><window.FindabilityScoreCards run={activeRun} /><window.LocalSignalAuditPanel run={activeRun} /><window.FindabilityTestTable run={activeRun} /><window.FindabilityRecommendationPanel run={activeRun} /></> : null}
    </main>;
  }

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