/* eslint-disable */
// Landing page components: Hero, SectionGrid, AskAI box, Interactive Roadmap.

function Hero() {
  const heroText = () =>
    "Aged Care and Disability Strategy, 2026 to 2030. " +
    "Gilgandra Shire Council’s plan for how we care for older people, " +
    "people living with disability, and the carers and families beside them " +
    "over the next five years.";
  return (
    <section className="hero" id="top">
      <div className="hero__bg" style={{ backgroundImage: "url(../../assets/photo-cover-aged-care.png)" }} />
      <div className="hero__veil" />
      <div className="shell hero__inner">
        <div>
          <div className="hero__url">{window.GSC_URL}</div>
          <h1 className="hero__title">Aged Care &amp;<br />Disability<br />Strategy</h1>
          <div className="hero__years">2026 — 2030</div>
          <p className="hero__sub">
            Gilgandra Shire Council&rsquo;s plan for how we care for older people,
            people living with disability, and the carers and families beside them
            over the next five years.
          </p>
          <div className="hero__listen">
            <SpeakButton getText={heroText} label="Listen to the introduction" />
          </div>
        </div>
        <div className="hero__logo-card">
          <img className="mark" src="../../assets/mark-live-enjoy-grow.png" alt="Live · Enjoy · Grow" />
          <span className="url-pill">gilgandra.nsw.gov.au</span>
        </div>
      </div>
    </section>
  );
}

function SectionGrid() {
  const cards = [
    { num: "01",  href: "introduction.html",         color: "#7DC141", title: "Introduction",                          sub: "Acknowledgement of Country, the General Manager’s message, our story, what this Strategy covers and the vision that guides it." },
    { num: "02",  href: "community-context.html",    color: "#AD2280", title: "Community & Service Context",            sub: "The services Council delivers today, who they reach, what the community told us and where the pressures are growing." },
    { num: "03",  href: "strategic-priorities.html", color: "#F26522", title: "Strategic Priorities & Actions",        sub: "Five priorities that will guide our work, with every action and task in full — from Support at Home to Build Workforce and Systems." },
    { num: "04",  href: "implementation.html",       color: "#52B9E8", title: "Implementation & Governance",            sub: "How we’ll deliver the Strategy, who is responsible, how we’ll monitor progress, and the references behind every claim." },
    { num: "PDF", href: "strategy.html",             color: "#F9D903", title: "Read the Strategy",                      sub: "Browse or download the full printed Strategy — cover, foreword, every chapter and the back cover — exactly as published." }
  ];
  const gridText = () => {
    const intro = "Read the Strategy. Four chapters plus the source document. " +
      "Each chapter mirrors a section of the printed Strategy. " +
      "Open one to read every word, every action and every task in full, or grab the PDF. ";
    const cardSummaries = cards.map(c => {
      const label = c.num === "PDF" ? "Read the Strategy" : `Section ${c.num}: ${c.title}`;
      return `${label}. ${c.sub}`;
    }).join(" ");
    return intro + cardSummaries;
  };
  return (
    <section className="section" id="sections">
      <div className="shell">
        <div className="section__head">
          <div>
            <div className="eyebrow">Read the Strategy</div>
            <h2>Four chapters plus the source document.</h2>
          </div>
          <SpeakButton getText={gridText} label="Listen to the chapter overview" />
        </div>
        <p className="lede">
          Each chapter mirrors a section of the printed Strategy. Open one to read
          every word, every action and every task in full — or grab the PDF.
        </p>
        <div className="section-grid section-grid--five">
          {cards.map(c => (
            <a key={c.num} href={c.href} className="section-card" style={{ "--card-color": c.color }}>
              <div className="section-card__num">{c.num === "PDF" ? "PDF" : `Section ${c.num}`}</div>
              <div className="section-card__title">{c.title}</div>
              <div className="section-card__sub">{c.sub}</div>
              <div className="section-card__cta">{c.num === "PDF" ? "Open document" : "Open chapter"} <span className="arrow">→</span></div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------------------------------------------------------------------------
// MicButton — voice input using the browser's native SpeechRecognition.
// Click to start, click to stop. Interim transcripts stream into the input
// as the user speaks; the final transcript replaces them. Renders nothing
// in browsers that don't support the Web Speech API (e.g. Firefox).
// ---------------------------------------------------------------------------
function MicButton({ onTranscript, disabled }) {
  const SR = typeof window !== "undefined" &&
    (window.SpeechRecognition || window.webkitSpeechRecognition);
  const supported = !!SR;
  const recognitionRef = React.useRef(null);
  const [listening, setListening] = React.useState(false);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (!supported) return;
    const recognition = new SR();
    recognition.lang = "en-AU";
    recognition.continuous = false;
    recognition.interimResults = true;
    recognition.maxAlternatives = 1;

    recognition.onresult = (e) => {
      let transcript = "";
      let isFinal = false;
      for (let i = 0; i < e.results.length; i++) {
        transcript += e.results[i][0].transcript;
        if (e.results[i].isFinal) isFinal = true;
      }
      onTranscript(transcript, isFinal);
    };
    recognition.onerror = (e) => {
      const map = {
        "no-speech":     "I didn’t catch that — try again.",
        "audio-capture": "No microphone detected.",
        "not-allowed":   "Microphone permission was denied.",
        "network":       "Network error during recognition.",
      };
      setError(map[e.error] || `Voice error: ${e.error}`);
      setListening(false);
    };
    recognition.onend = () => setListening(false);

    recognitionRef.current = recognition;
    return () => { try { recognition.abort(); } catch (_) {} };
  }, [supported, onTranscript]);

  if (!supported) return null;

  const toggle = () => {
    setError(null);
    if (listening) {
      try { recognitionRef.current.stop(); } catch (_) {}
      return;
    }
    try {
      recognitionRef.current.start();
      setListening(true);
    } catch (_) {
      setError("Could not start microphone");
    }
  };

  return (
    <React.Fragment>
      <button
        type="button"
        className={`mic-btn ${listening ? "is-listening" : ""}`}
        onClick={toggle}
        disabled={disabled}
        aria-label={listening ? "Stop recording" : "Speak your question"}
        aria-pressed={listening}
        title={listening ? "Stop recording" : "Speak your question"}
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          {listening ? (
            <circle cx="12" cy="12" r="6" />
          ) : (
            <React.Fragment>
              <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />
              <path d="M19 10v2a7 7 0 0 1-14 0v-2" />
              <line x1="12" y1="19" x2="12" y2="23" />
              <line x1="8" y1="23" x2="16" y2="23" />
            </React.Fragment>
          )}
        </svg>
      </button>
      {error && <span className="mic-btn__error" role="status">{error}</span>}
    </React.Fragment>
  );
}

function AskAI() {
  const [q, setQ] = React.useState("");
  const [answer, setAnswer] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  // Snapshot of the input value before voice recognition started — interim
  // results are appended onto this so they don’t overwrite typed text.
  const voiceBaseRef = React.useRef("");

  // Each prompt has a short, human label shown on the button and a fuller
  // question that's actually sent to the assistant.
  const examples = [
    { label: "Ask me about our vision",              question: "What is the vision of the Strategy?" },
    { label: "Ask me about Cooee Lodge",             question: "What is happening with Cooee Lodge?" },
    { label: "Ask me about NDIS reform",             question: "How will NDIS reform affect Orana Living?" },
    { label: "Ask me about Support at Home",         question: "How will Council grow Support at Home?" },
    { label: "Ask me about Carlginda Enterprises",   question: "What is planned for Carlginda Enterprises?" },
    { label: "Ask me about our workforce",           question: "How is the workforce being strengthened?" },
  ];

  const askText = () =>
    "Ask a question. Don’t want to read fifty-eight pages? Ask the Strategy. " +
    "Type a question about the Strategy, or click the microphone to speak it. " +
    "Answers are drawn from the document itself.";

  const submit = async (question) => {
    const trimmed = (question || q).trim();
    if (!trimmed) return;

    const endpoint = window.GSC_AI_ENDPOINT;
    if (!endpoint) {
      setError(
        "The AI assistant isn’t configured yet. " +
        "Deploy the Cloudflare Worker in ai-worker/ and paste its URL into scripts/config.js."
      );
      return;
    }

    setLoading(true); setError(null); setAnswer(null);

    try {
      const system = window.buildSystemPrompt();
      const response = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question: trimmed, system }),
      });

      let payload = null;
      try { payload = await response.json(); } catch (_) { /* not JSON */ }

      if (!response.ok) {
        const msg = (payload && payload.error) ? payload.error : `HTTP ${response.status}`;
        throw new Error(msg);
      }
      const text = (payload && payload.text) ? payload.text : "";
      setAnswer(text || "(The assistant didn’t return an answer. Try rephrasing.)");
    } catch (e) {
      console.error(e);
      setError(`Sorry — couldn’t reach the assistant. ${e.message || ""}`.trim());
    } finally {
      setLoading(false);
    }
  };

  // Voice-input callback. Called repeatedly with interim transcripts and once
  // more with the final transcript. We snapshot the typed text the first time
  // a transcript arrives so the user’s existing text isn’t wiped.
  const handleTranscript = React.useCallback((transcript, isFinal) => {
    const base = voiceBaseRef.current || "";
    const joined = base ? `${base} ${transcript}`.replace(/\s+/g, " ").trim() : transcript;
    setQ(joined);
    if (isFinal) voiceBaseRef.current = joined;
  }, []);

  // Keep the voice base in sync with typed edits: if the user clears the
  // box, the next recording starts fresh.
  React.useEffect(() => { if (!q) voiceBaseRef.current = ""; }, [q]);

  return (
    <section className="section section--cream" id="ask">
      <div className="shell">
        <div className="section__head">
          <div>
            <div className="eyebrow">Ask a question</div>
            <h2>Don&rsquo;t want to read 58 pages? Ask the Strategy.</h2>
          </div>
          <SpeakButton getText={askText} label="Listen to this section" />
        </div>
        <p className="lede">
          Type a question about the Strategy and we&rsquo;ll surface what it says,
          or click the microphone to speak it. Answers are drawn from the document itself.
        </p>

        <div className="ai-box">
          <form className="ai-box__field" onSubmit={(e) => { e.preventDefault(); submit(); }}>
            <input
              type="text"
              value={q}
              onChange={(e) => { voiceBaseRef.current = e.target.value; setQ(e.target.value); }}
              placeholder="e.g. What is happening with Cooee Lodge?"
              aria-label="Ask a question about the Strategy"
            />
            <MicButton onTranscript={handleTranscript} disabled={loading} />
            <button type="submit" className="ai-box__btn" disabled={loading || !q.trim()}>
              {loading ? "Asking…" : "Ask"}
            </button>
          </form>
          <div className="ai-box__prompts">
            {examples.map((ex, i) => (
              <button
                key={i}
                type="button"
                className="ai-box__prompt"
                onClick={() => { voiceBaseRef.current = ex.question; setQ(ex.question); submit(ex.question); }}
              >
                {ex.label}
              </button>
            ))}
          </div>
          {loading && (
            <div className="ai-box__answer">
              <span className="ai-box__loading">Reading the Strategy…</span>
            </div>
          )}
          {error && <div className="ai-box__answer" style={{ borderLeftColor: "var(--gsc-red)" }}>{error}</div>}
          {answer && <div className="ai-box__answer">{answer}</div>}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, SectionGrid, AskAI, MicButton });
