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

  function unwrap(response) { return response && response.data !== undefined ? response.data : response; }

  function FreeSeoSchemaBuilderView() {
    const api = global.JS_API && global.JS_API.freeSeo && global.JS_API.freeSeo.schemaBuilder;
    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState('');
    const [run, setRun] = React.useState(null);
    const [runs, setRuns] = React.useState([]);
    const [selectedSchema, setSelectedSchema] = React.useState(null);

    React.useEffect(() => { if (api) api.listRuns({ limit: 10 }).then((res) => setRuns(unwrap(res).items || [])).catch(() => null); }, []);

    function create(payload) {
      setLoading(true); setError('');
      api.createRun(payload).then((res) => {
        const data = unwrap(res);
        setRun(data); setSelectedSchema((data.generatedSchemas || [])[0] || null);
        setRuns([data].concat(runs));
      }).catch((err) => setError(err.message || String(err))).finally(() => setLoading(false));
    }

    function exportRun(format) {
      if (!run) return;
      api.exportRun(run.id, format || 'zip').then(() => null).catch((err) => setError(err.message || String(err)));
    }

    if (!api) return <div className="free-seo-page"><h1>Schema Builder</h1><p>Schema Builder client is not loaded.</p></div>;
    const summary = run && run.summary || {};

    return <div className="free-seo-page free-seo-schema-builder">
      <header className="free-seo-hero"><p className="eyebrow">Free SEO Lab / Patch 06</p><h1>Schema and Rich Result Opportunity Builder</h1><p>Generate local JSON-LD, validation evidence, and install snippets without paid API keys.</p></header>
      {error ? <div className="alert error">{error}</div> : null}
      <SchemaBuildForm onSubmit={create} loading={loading} />
      {run ? <section className="free-seo-card"><h2>Run summary</h2><div className="metric-grid"><div><strong>{summary.schemaCount || 0}</strong><span>Schemas</span></div><div><strong>{summary.validSchemaCount || 0}</strong><span>Valid</span></div><div><strong>{summary.highPriorityCount || 0}</strong><span>High priority</span></div><div><strong>{Math.round((summary.readinessScore || 0) * 100)}</strong><span>Readiness</span></div></div><div className="actions"><button onClick={() => exportRun('html')}>Export HTML</button><button onClick={() => exportRun('json')}>Export JSON</button><button onClick={() => exportRun('zip')}>Export ZIP</button></div></section> : null}
      {run ? <SchemaOpportunityTable opportunities={run.opportunities || []} /> : null}
      {run ? <div className="grid two"><JsonLdPreview schemas={run.generatedSchemas || []} selected={selectedSchema} onSelect={setSelectedSchema} /><SchemaValidationPanel schema={selectedSchema} /></div> : null}
      {run ? <SchemaInstallGuide schema={selectedSchema} /> : null}
      <section className="free-seo-card"><h3>Recent schema runs</h3>{runs.length ? <ul>{runs.map((item) => <li key={item.id}><button type="button" onClick={() => { setRun(item); setSelectedSchema((item.generatedSchemas || [])[0] || null); }}>{item.websiteUrl || item.id}</button> <span className="muted">{item.status}</span></li>)}</ul> : <p>No recent runs loaded.</p>}</section>
    </div>;
  }

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