/* global React */
const { useState: useStateD, useRef: useRefD, useEffect: useEffectD } = React;

/* ──────────────────────────────────────────
   THE DISCOVERY ENGINE
   The page's centerpiece. User types in plain English →
   Claude returns a structured list of automations.
   ────────────────────────────────────────── */

const DISCOVERY_PROMPT = `You are the AI inside Cayres Labs' homepage — a boutique studio that builds AI automation systems for businesses. A potential client just described their business in 1–3 sentences.

Your job: identify the 5 most valuable automations we could build for THEIR specific business — not generic advice. Be opinionated and concrete. Reference the specific tools, workflows, or customer touchpoints they mentioned.

Reply with ONLY a JSON object — no prose, no markdown fences. Schema:
{
  "summary": "ONE punchy sentence in plain English describing where their biggest leverage is. Max 22 words. No corporate fluff.",
  "recommendations": [
    {
      "name": "Short title — concrete, verb-led",
      "why": "1–2 sentences. Reference their specific business. Mention the leak we'd close.",
      "impact": "high" | "medium",
      "tag": "2–4 word category, ALL CAPS"
    }
  ]
}

Rules:
- Exactly 5 recommendations.
- Order by impact (highest first). At least 2 should be marked "high".
- Avoid generic "chatbot" / "AI assistant" recommendations unless very specific.
- Voice: direct, founder-to-founder. No hype words ("revolutionize", "leverage", "synergize").
- Each "why" must reference something the user actually said.`;

const QUICK_FILLS = [
  "I run a 4-chair dental practice in San Diego, ~200 calls a month, my front desk misses 1 in 3 after hours.",
  "Two-truck plumbing company, we book through phone and Yelp, my wife runs the office.",
  "Boutique law firm, 6 attorneys, intake forms come in and sometimes sit for a day before we respond.",
  "I have an HVAC business, 12 techs, leads come from Google ads but our follow-up is whoever has time.",
];

function buildOfflineFallback(input) {
  // Used if the AI helper fails — generic but still relevant.
  return {
    summary:
      "Your fastest wins are speed-to-lead and follow-up — the rest only matters once those are airtight.",
    recommendations: [
      {
        name: "Missed-call text-back in 60 seconds",
        why: "Every missed call you mentioned becomes a text the prospect can reply to instantly, before they call the next listing on Google.",
        impact: "high",
        tag: "Speed to Lead",
      },
      {
        name: "Instant form-response sequence",
        why: "The moment someone submits a form, an AI replies in your voice, qualifies them, and books a call slot — no human required.",
        impact: "high",
        tag: "Inbound",
      },
      {
        name: "Quote follow-up that doesn't quit",
        why: "Multi-day SMS + email sequence runs until the prospect books, declines, or opts out — replacing the 'oh I forgot to follow up' moments.",
        impact: "high",
        tag: "Pipeline",
      },
      {
        name: "Automated review requests after every job",
        why: "Once a job is marked complete in your system, the customer gets a review request at the time most likely to convert.",
        impact: "medium",
        tag: "Reputation",
      },
      {
        name: "Lead qualification + routing",
        why: "Real opportunities go straight to the right person; tire-kickers get auto-replies. Your team stops being a switchboard.",
        impact: "medium",
        tag: "Operations",
      },
    ],
  };
}

// Production Discovery Engine endpoint (Cloudflare Worker).
// Key isolation, rate limiting, input/output validation all live server-side.
const DISCOVERY_ENDPOINT = "https://cayres-discovery.arturcayres.workers.dev";

async function runDiscovery(input) {
  try {
    const r = await fetch(DISCOVERY_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ input }),
    });
    const data = await r.json();
    // The worker always returns valid JSON — real recs or its own fallback.
    if (
      data &&
      Array.isArray(data.recommendations) &&
      data.recommendations.length > 0
    ) {
      return data;
    }
    return buildOfflineFallback(input);
  } catch (e) {
    // Network failure / worker unreachable → local fallback, never a broken state.
    return buildOfflineFallback(input);
  }
}

function Discovery() {
  const [input, setInput] = useStateD("");
  const [loading, setLoading] = useStateD(false);
  const [result, setResult] = useStateD(null);
  const taRef = useRefD(null);

  const submit = async (val) => {
    const v = (val ?? input).trim();
    if (!v || loading) return;
    setInput(v);
    setLoading(true);
    setResult(null);
    const r = await runDiscovery(v);
    setLoading(false);
    setResult(r);
  };

  const reset = () => {
    setInput("");
    setResult(null);
    setLoading(false);
    setTimeout(() => taRef.current?.focus(), 50);
  };

  const onKey = (e) => {
    if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
      e.preventDefault();
      submit();
    }
  };

  return (
    <div className="discovery" id="discovery">
      {/* INPUT SIDE */}
      <div className="disco-input-card">
        <div className="disco-label">
          <span className="pip" aria-hidden="true"></span>
          <span>tell us about your business · in plain english</span>
        </div>
        <textarea
          ref={taRef}
          className="disco-textarea"
          placeholder="e.g. I run a 4-chair dental practice in San Diego, we get about 200 calls a month, and my front desk misses 1 in 3 after hours…"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={onKey}
          rows={5}
          disabled={loading}
        />

        <div className="disco-quick">
          {QUICK_FILLS.map((q, i) => (
            <button
              key={i}
              className="disco-chip"
              onClick={() => {
                setInput(q);
                submit(q);
              }}
              disabled={loading}
              title={q}
            >
              {q.split(",")[0].replace(/^I (run|have)\s+/i, "")}
            </button>
          ))}
        </div>

        <div className="disco-actions">
          <span className="disco-hint">⌘ + ↵ to send</span>
          <button
            className="disco-submit"
            onClick={() => submit()}
            disabled={!input.trim() || loading}
          >
            {loading ? "Analyzing…" : "Show me what to automate"}
            <span aria-hidden="true">→</span>
          </button>
        </div>
      </div>

      {/* OUTPUT SIDE */}
      <div className="disco-output">
        <div className="disco-output-head">
          <span className="disco-output-title">
            {loading
              ? "Cayres AI · scanning…"
              : result
                ? "Cayres AI · 5 recommendations"
                : "Cayres AI · awaiting input"}
          </span>
          {result && (
            <span className="disco-output-title">
              {String(result.recommendations.length).padStart(2, "0")} items
            </span>
          )}
        </div>

        {!loading && !result && (
          <div className="disco-empty">
            "Tell me about your business and I'll show you exactly where the
            money is leaking — and what we'd build to plug it."
          </div>
        )}

        {loading && (
          <div className="disco-loading" aria-live="polite">
            <div className="disco-skel"></div>
            <div className="disco-skel"></div>
            <div className="disco-skel"></div>
            <div className="disco-skel"></div>
          </div>
        )}

        {result && (
          <div>
            {result.recommendations.map((r, i) => (
              <div
                key={i}
                className="disco-rec"
                style={{ animationDelay: `${i * 90}ms` }}
              >
                <div className="idx">0{i + 1}</div>
                <div className="body">
                  <div className="name">{r.name}</div>
                  <div className="why">{r.why}</div>
                </div>
                <div className="impact">
                  {r.tag || "AUTOMATION"}
                  <br />
                  <span className={`h ${r.impact === "high" ? "high" : ""}`}>
                    {r.impact === "high" ? "high impact" : "med impact"}
                  </span>
                </div>
              </div>
            ))}

            {result.summary && (
              <div className="disco-summary">"{result.summary}"</div>
            )}

            <div className="disco-followup">
              <a href="#contact" className="arrow-cta">
                Build this with us <span aria-hidden="true">→</span>
              </a>
              <button className="reset" onClick={reset}>
                ↻ try another business
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.Discovery = Discovery;
