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

  function parseLines(value) {
    return String(value || '').split('\n').map((line) => line.trim()).filter(Boolean);
  }

  function safeJson(value, fallback) {
    try { return JSON.parse(value); } catch (error) { return fallback; }
  }

  function FindabilityRunForm({ onRunCreated }) {
    const [websiteUrl, setWebsiteUrl] = React.useState('');
    const [businessName, setBusinessName] = React.useState('');
    const [businessType, setBusinessType] = React.useState('');
    const [phone, setPhone] = React.useState('');
    const [street, setStreet] = React.useState('');
    const [city, setCity] = React.useState('');
    const [region, setRegion] = React.useState('');
    const [services, setServices] = React.useState('');
    const [locations, setLocations] = React.useState('');
    const [questions, setQuestions] = React.useState('');
    const [pagesJson, setPagesJson] = React.useState('[{"url":"https://example.com/service","title":"Service page","textContent":"Business name offers service in location. Call phone.","schemaTypes":["LocalBusiness","Service"]}]');
    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState('');

    async function submit(event) {
      event.preventDefault();
      setLoading(true); setError('');
      try {
        const payload = {
          websiteUrl,
          businessProfile: { name: businessName, businessType, telephone: phone, address: { streetAddress: street, addressLocality: city, addressRegion: region }, areaServed: parseLines(locations) },
          services: parseLines(services).map((name) => ({ name })),
          locations: parseLines(locations).map((name) => ({ name, region })),
          questions: parseLines(questions),
          pages: safeJson(pagesJson, []),
          options: { includeStoredEvidence: true, maxQuestions: 60 }
        };
        const response = await global.JS_API.freeSeo.aiFindability.createRun(payload);
        onRunCreated && onRunCreated(response.data || response);
      } catch (err) { setError(err.message || 'Unable to create AI findability run.'); }
      finally { setLoading(false); }
    }

    return <form className="free-seo-card" onSubmit={submit}>
      <h2>Create AI Findability Test</h2>
      <p className="muted">Score whether service/location questions have enough local evidence for AI-style answer systems. No paid API keys required.</p>
      {error ? <div className="alert alert-error">{error}</div> : null}
      <div className="grid two">
        <label>Website URL<input value={websiteUrl} onChange={(e) => setWebsiteUrl(e.target.value)} placeholder="https://example.com" required /></label>
        <label>Business name<input value={businessName} onChange={(e) => setBusinessName(e.target.value)} required /></label>
        <label>Business type<input value={businessType} onChange={(e) => setBusinessType(e.target.value)} placeholder="Dentist, plumber, agency..." /></label>
        <label>Phone<input value={phone} onChange={(e) => setPhone(e.target.value)} /></label>
        <label>Street<input value={street} onChange={(e) => setStreet(e.target.value)} /></label>
        <label>City<input value={city} onChange={(e) => setCity(e.target.value)} /></label>
        <label>Region/state<input value={region} onChange={(e) => setRegion(e.target.value)} /></label>
        <label>Services, one per line<textarea value={services} onChange={(e) => setServices(e.target.value)} rows="5" /></label>
        <label>Locations served, one per line<textarea value={locations} onChange={(e) => setLocations(e.target.value)} rows="5" /></label>
        <label>Manual questions, optional<textarea value={questions} onChange={(e) => setQuestions(e.target.value)} rows="5" /></label>
      </div>
      <label>Manual page evidence JSON<textarea value={pagesJson} onChange={(e) => setPagesJson(e.target.value)} rows="8" /></label>
      <button className="button primary" type="submit" disabled={loading}>{loading ? 'Running...' : 'Run AI Findability Test'}</button>
    </form>;
  }

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