// Klombic — Free instant-check widget
//
// Sits on the homepage between the hero and the SixChecksSection. Lets a
// visitor type a brief, get 3 LLM-generated candidate names with 4 automated
// checks each (.com, memorability, sound-symbolism, pronounceability) + a
// one-click manual USPTO TESS verify link, then hands them off into the paid
// wizard with the names prefilled.
//
// Automated checks INCLUDED in free (this widget):
//   • .com availability (RDAP)
//   • Memorability score (algorithmic, Miller 1956 + Lowrey-Shrum 2007)
//   • Sound-symbolism vibe (algorithmic, Klink 2000)
//   • Pronounceability EN+ES (algorithmic)
// Plus a per-name "→ Verify on USPTO TESS" manual link.
//
// Reserved for paid Quick ($9.99) — explicitly listed in the CTA:
//   • Automated USPTO TESS scraping in chosen IC class (no manual click)
//   • Cross-language slur scan (15+ languages)
//   • Multi-TLD check (.io, .app, .dev, etc)
//   • TM-extension risk in adjacent IC classes
//   • Shopify slug check
//   • 30 candidates → top 3 ranked winners (vs 3 here)
//   • Ranked PDF for the attorney

// IC class options — same 12 common classes as the order wizard.
const INSTANT_IC_CLASSES = [
  { id: "042", label: "042 — Software / SaaS / hosting" },
  { id: "035", label: "035 — Advertising · retail · e-commerce" },
  { id: "009", label: "009 — Hardware · downloadable software" },
  { id: "041", label: "041 — Education · entertainment" },
  { id: "025", label: "025 — Clothing · apparel · fashion" },
  { id: "030", label: "030 — Coffee · tea · snacks · baked goods" },
  { id: "029", label: "029 — Meat · dairy · prepared foods" },
  { id: "003", label: "003 — Cosmetics · beauty · personal care" },
  { id: "044", label: "044 — Medical · health · telemedicine" },
  { id: "045", label: "045 — Legal · security · dating · social" },
  { id: "036", label: "036 — Financial services · insurance" },
  { id: "043", label: "043 — Restaurants · cafes · hotels" },
];

const InstantCheck = ({ go }) => {
  const [brief, setBrief] = React.useState("");
  const [icClass, setIcClass] = React.useState("042");
  const [customName, setCustomName] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [result, setResult] = React.useState(null);
  // Anchors auto-scroll once results land so visitors don't miss them below the form.
  const resultsRef = React.useRef(null);

  const briefValid = brief.trim().length >= 15;
  // Custom name is optional but must pass the same charset rule as the wizard if provided
  const customNameValid = !customName.trim() || /^[A-Za-z0-9\-' ]{1,30}$/.test(customName.trim());

  const run = async () => {
    if (!briefValid || !customNameValid || submitting) return;
    setSubmitting(true);
    setError(null);
    setResult(null);
    try {
      const r = await fetch("/api/instant-check", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          brief: brief.trim(),
          icClass,
          customName: customName.trim() || undefined,
        }),
      });
      const data = await r.json();
      if (!r.ok) {
        setError(data.error || "Something went wrong. Try again.");
        setSubmitting(false);
        return;
      }
      setResult(data);
      setSubmitting(false);
      // Wait one render tick so the results DOM is mounted before scrolling.
      setTimeout(() => {
        resultsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
      }, 100);
    } catch (e) {
      setError("Network error. Try again or run a paid check.");
      setSubmitting(false);
    }
  };

  const handoff = () => {
    if (!result?.candidates) return;
    const names = result.candidates.map(c => c.name).join(",");
    // Use a query param the order wizard will read on mount
    const url = new URL(window.location);
    url.searchParams.set("page", "order");
    url.searchParams.set("names", names);
    url.searchParams.set("ic", result.icClass || "042");
    window.history.pushState({}, "", url);
    go("order");
  };

  return (
    <section className="instant-check-section" id="try-it-free">
      <div className="page">
        <div className="ic-header">
          <span className="ic-eyebrow">✦ Try Klombic free</span>
          <h2 className="ic-title">4 checks per name. No signup. No card.</h2>
          <p className="ic-lead">
            Describe your brand in a sentence or two. We'll generate 3 candidate
            names and run 4 automated checks on each — .com availability,
            memorability, sound-symbolism, and pronounceability — plus a
            one-click USPTO TESS verify link.
          </p>
        </div>

        <div className="ic-card">
          <div className="ic-field">
            <label>Describe your brand · 1–2 sentences</label>
            <textarea
              value={brief}
              onChange={(e) => setBrief(e.target.value.slice(0, 500))}
              placeholder="e.g. A productivity tool for solo founders to track customer feedback across email, Slack, and Reddit. Modern, calm, trustworthy."
              rows={3}
              maxLength={500}
            />
            <span className="ic-counter">
              {brief.length} / 500 · {briefValid ? "ready" : `${Math.max(0, 15 - brief.length)} more chars to start`}
            </span>
          </div>

          <div className="ic-field">
            <label>USPTO class · what your business does</label>
            <select value={icClass} onChange={(e) => setIcClass(e.target.value)}>
              {INSTANT_IC_CLASSES.map(c => (
                <option key={c.id} value={c.id}>{c.label}</option>
              ))}
            </select>
          </div>

          <div className="ic-field">
            <label>
              Got a name in mind? <span className="ic-optional">(optional · we'll check it alongside 2 AI suggestions)</span>
            </label>
            <input
              type="text"
              value={customName}
              onChange={(e) => setCustomName(e.target.value.slice(0, 30))}
              placeholder="e.g. Verridge"
              maxLength={30}
              autoComplete="off"
              autoCorrect="off"
              spellCheck="false"
              className={!customNameValid ? "ic-invalid" : ""}
            />
            {!customNameValid && (
              <span className="ic-counter ic-counter-warn">
                Letters, digits, hyphen, apostrophe, space only · 1–30 chars
              </span>
            )}
          </div>

          <div className="ic-disclaimer">
            <div className="ic-disclaimer-title">What this free check does NOT cover</div>
            <ul>
              <li><b>Automated USPTO conflict screening</b> — only a manual TESS verify link per name (you click through to USPTO yourself)</li>
              <li><b>Cross-language slur scan</b> across 15+ languages — catches name disasters like Honda's "Fitta"</li>
              <li><b>Multi-TLD availability</b> — only .com, not .io / .app / .dev / +5</li>
              <li><b>TM-extension risk</b> in IC classes adjacent to yours</li>
              <li><b>Phonetic-similar §2(d) screening</b> + common-law sweep (Premium-tier checks)</li>
              <li>Only 3 generated names · paid Quick generates 30 and ranks the top 3 winners</li>
            </ul>
            <p className="ic-disclaimer-foot">
              This is a preliminary signal — not legal clearance. For pre-filing due
              diligence, run paid Quick ($9.99) or consult a trademark attorney.
            </p>
          </div>

          <button
            className="ic-cta"
            onClick={run}
            disabled={!briefValid || !customNameValid || submitting}
          >
            {submitting ? "Generating + running checks…" : "Generate 3 names + run 4 free checks"}
          </button>

          {submitting && (
            <div className="ic-progress">
              Generating names · checking USPTO links · RDAP-lookup .com · scoring memorability/sound/pronounce…
              <span className="ic-progress-dot">●</span>
            </div>
          )}

          {error && <div className="ic-error">{error}</div>}
        </div>

        {result && result.candidates && (
          <div className="ic-results" ref={resultsRef}>
            <div className="ic-results-flag">✓ Your 3 names · 4 checks ran · scroll for details</div>
            <div className="ic-results-header">
              <span className="ic-results-label">
                {result.candidates.length} candidates · 4 checks ran · instant on-screen results
              </span>
              <span className="ic-results-sub">
                IC class {result.icClass} · {result.candidates.filter(c => c.com?.available).length} of {result.candidates.length} have .com available
              </span>
            </div>

            <div className="ic-checks-ran">
              <div className="ic-checks-ran-title">What we just ran for you</div>
              <ul>
                <li><b>.com availability</b> via RDAP (Verisign authoritative)</li>
                <li><b>Memorability score</b> — length, initial-letter rarity, vowel balance (Miller 1956 + Lowrey-Shrum 2007)</li>
                <li><b>Sound-symbolism vibe</b> — heavy/light × hard/soft axes (Klink 2000)</li>
                <li><b>Pronounceability</b> — EN + ES consonant-cluster heuristic (0–1)</li>
                <li><b>Manual USPTO TESS link</b> per name — click to verify against live registrations yourself</li>
              </ul>
              <p className="ic-checks-ran-foot">
                No PDF, no email, no signup. Paid Quick ($9.99) adds the 4 disaster-catching checks below
                <i> and</i> delivers a ranked PDF within 24 hours.
              </p>
            </div>

            <div className="ic-cards">
              {result.candidates.map((c, idx) => {
                const comAvailable = c.com?.available === true;
                const comTaken = c.com?.available === false;
                const memHigh = c.memorability?.interpretation === "high";
                const pronounceGood = (c.pronounce?.en ?? 0) >= 0.85 && (c.pronounce?.es ?? 0) >= 0.85;
                const looksGood = comAvailable && memHigh && pronounceGood;
                return (
                  <div key={idx} className={`ic-name-card ${looksGood ? "ic-name-card--clean" : ""} ${c.source === "customer" ? "ic-name-card--yours" : ""}`}>
                    <div className="ic-name-row">
                      <h3 className="ic-name">{c.name}</h3>
                      <div className="ic-name-badges">
                        {c.source === "customer" && <span className="ic-badge ic-badge-yours">Your name</span>}
                        {looksGood && <span className="ic-badge">Looks good</span>}
                      </div>
                    </div>
                    <div className="ic-checks">
                      <div className="ic-check-row">
                        <span className="ic-check-lbl">{c.com?.domain || `${c.name.toLowerCase()}.com`}</span>
                        <span className={`ic-check-val ${comAvailable ? "ok" : comTaken ? "no" : "warn"}`}>
                          {comAvailable ? "available" : comTaken ? "taken" : "—"}
                        </span>
                      </div>
                      <div className="ic-check-row">
                        <span className="ic-check-lbl">Memorability</span>
                        <span className={`ic-check-val ${memHigh ? "ok" : "score"}`}>
                          {c.memorability?.composite?.toFixed(2)} · {c.memorability?.interpretation}
                        </span>
                      </div>
                      <div className="ic-check-row">
                        <span className="ic-check-lbl">Vibe</span>
                        <span className="ic-check-val score">{c.sound?.vibe}</span>
                      </div>
                      <div className="ic-check-row">
                        <span className="ic-check-lbl">Pronounce EN / ES</span>
                        <span className={`ic-check-val ${pronounceGood ? "ok" : "score"}`}>
                          {c.pronounce?.en?.toFixed(2)} / {c.pronounce?.es?.toFixed(2)}
                        </span>
                      </div>
                      <div className="ic-check-row ic-uspto-row">
                        <span className="ic-check-lbl">USPTO · IC {result.icClass}</span>
                        <a
                          href={c.usptoManualUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="ic-uspto-link"
                        >
                          → Verify on TESS
                        </a>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            <div className="ic-paid-cta">
              <div className="ic-paid-header">
                <span className="ic-paid-eyebrow">Want the full report?</span>
                <h3>4 of 8 checks shown — plus a manual USPTO link. Paid Quick adds automated USPTO + the disaster-catching checks.</h3>
              </div>
              <ul className="ic-paid-list">
                {(result.paid?.extras || []).map((x, i) => (
                  <li key={i}>{x}</li>
                ))}
              </ul>
              <div className="ic-paid-actions">
                <button className="ic-paid-btn" onClick={handoff}>
                  Run paid Quick on these 3 names — ${result.paid?.price?.toFixed(2) || "9.99"} ↗
                </button>
                <a className="ic-paid-link" href="#" onClick={(e) => { e.preventDefault(); go("sample"); }}>
                  See a sample paid report →
                </a>
              </div>
            </div>
          </div>
        )}

        {!result && !submitting && (
          <p className="ic-footnote">
            4 free automated checks + 1 manual USPTO link per name. Generates 3 names from your brief. Paid Quick ($9.99) generates 30 → ranks the top 3 with automated USPTO + all 8 checks per name plus a PDF.
          </p>
        )}
      </div>
    </section>
  );
};

window.InstantCheck = InstantCheck;
