// Global FAQ page — aggregates per-service FAQs + general business questions.
function FAQPage({ go }) {
  const services = window.SERVICE_PAGES || {};

  // Wrap text matches as inline links.
  // subs: array of { match: RegExp|string, target: "studio"|"submit"|"service:01"|... }
  function withLinks(text, subs) {
    let nodes = [text];
    subs.forEach(({ match, target }) => {
      const next = [];
      const re = match instanceof RegExp ? match : new RegExp(match.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
      nodes.forEach(node => {
        if (typeof node !== "string") { next.push(node); return; }
        let last = 0, m, i = 0;
        re.lastIndex = 0;
        while ((m = re.exec(node)) !== null) {
          if (m.index > last) next.push(node.slice(last, m.index));
          next.push(
            <button
              key={`${target}-${m.index}-${i++}`}
              type="button"
              className="faq-inline-link"
              onClick={() => go(target)}
            >{m[0]}</button>
          );
          last = m.index + m[0].length;
          if (m[0].length === 0) re.lastIndex++;
        }
        if (last < node.length) next.push(node.slice(last));
      });
      nodes = next;
    });
    return <>{nodes}</>;
  }

  // Auto-linker: turns common references inside string answers into clickable links.
  function withLinks2(text, subs) {
    let nodes = [text];
    subs.forEach(({ match, target }) => {
      const next = [];
      const re = match instanceof RegExp ? new RegExp(match.source, match.flags.includes("g") ? match.flags : match.flags + "g") : new RegExp(match.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
      nodes.forEach(node => {
        if (typeof node !== "string") { next.push(node); return; }
        let last = 0, m, i = 0;
        re.lastIndex = 0;
        while ((m = re.exec(node)) !== null) {
          if (m.index > last) next.push(node.slice(last, m.index));
          const t = typeof target === "function" ? target(m) : target;
          next.push(
            <button
              key={`al-${m.index}-${i++}`}
              type="button"
              className="faq-inline-link"
              onClick={() => go(t)}
            >{m[0]}</button>
          );
          last = m.index + m[0].length;
          if (m[0].length === 0) re.lastIndex++;
        }
        if (last < node.length) next.push(node.slice(last));
      });
      nodes = next;
    });
    return <>{nodes}</>;
  }
  function autoLinkV2(text) {
    if (typeof text !== "string") return text;
    return withLinks2(text, [
      { match: /\(see (\d{2})\)/g, target: (m) => `service:${m[1]}` },
      { match: /service (\d{2})/g, target: (m) => `service:${m[1]}` },
      { match: /Submit page/g, target: "submit" },
      { match: /composer page/g, target: "composer" },
      { match: /Studio estimator|the estimator|The estimator/g, target: "studio" }
    ]);
  }

  const generalFaq = [
    { q: "What is Romanowski Studio?",
      a: "A studio offering professional music engraving, score and part preparation, orchestration, arranging, transposition, notation digitisation, audio mockups and printing. Run by Maciej Romanowski — composer and engraver." },
    { q: "How do I get a quote for music engraving or score preparation?",
      a: <>Use the <button type="button" className="faq-inline-link" onClick={() => go("studio")}>Studio estimator</button> for an indicative figure based on ensemble, page count and turnaround. A firm quote is issued on submission of score materials. Most projects are quoted within one working day. Projects marked urgent are reviewed instantly — we'll get back to you straight away to confirm whether we're able to take it on.</>,
      aText: "Use the Studio estimator for an indicative figure based on ensemble, page count and turnaround. A firm quote is issued on submission of score materials. Most projects are quoted within one working day. Projects marked urgent are reviewed instantly — we'll get back to you straight away to confirm whether we're able to take it on." },
    { q: "Where is the studio based?",
      a: "London, UK. Work is delivered worldwide — most projects run remotely, with materials submitted by upload and finished work delivered as PDF or by physical despatch from the print room. If you're based in London I will personally deliver the music, if you request for it to be printed, time permitting." },
    { q: "How do I submit a score for a quote or for work to begin?",
      a: withLinks(
        "Use the Submit page. Accepted file types: Sibelius 8 Ultimate and older (.sib), Dorico (.dorico), MusicXML (.musicxml / .mxl), PDF, and image scans (300 DPI minimum) of handwritten manuscript. Files up to 50MB upload directly; larger files via WeTransfer link.",
        [{ match: /Submit page/g, target: "submit" }]
      ),
      aText: "Use the Submit page. Accepted file types: Sibelius 8 Ultimate and older (.sib), Dorico (.dorico), MusicXML (.musicxml / .mxl), PDF, and image scans (300 DPI minimum) of handwritten manuscript. Files up to 50MB upload directly; larger files via WeTransfer link." },
    { q: "What software does the studio use?",
      a: "Engraving and notation are produced in Sibelius 8 Ultimate and Dorico Pro, with MusicXML and PDF used for cross-platform interchange. For working with midi files I run Cubase 15 Pro. Source files can be supplied on request." },
    { q: "What's the setup for audio mockups and orchestral demos?",
      a: withLinks(
        "Mockups are produced in Cubase 15 Pro — Spitfire, Cinematic Studio Series, Heavyocity, Cinesamples strings, winds, brass, percussion and pianos — bounced to stem and stereo mix. See service 06 for the full workflow.",
        [{ match: /service 06/g, target: "service:06" }]
      ),
      aText: "Mockups are produced in Cubase 15 Pro — Spitfire, Cinematic Studio Series, Heavyocity, Cinesamples strings, winds, brass, percussion and pianos — bounced to stem and stereo mix. See service 06 for the full workflow." },
    { q: "What's used for printing and binding?",
      a: withLinks(
        "In-house printing on heavyweight uncoated stock, with options for saddle-stitch booklets and comb binding for parts that need to lay flat on the stand. An enterprise-grade print machine handles any job thrown at it, at volume and to a professional finish. Print can be ordered alongside engraving or for files supplied by the client. See service 07 for the full print spec.",
        [{ match: /service 07/g, target: "service:07" }]
      ),
      aText: "In-house printing on heavyweight uncoated stock, with options for saddle-stitch booklets and comb binding for parts that need to lay flat on the stand. An enterprise-grade print machine handles any job thrown at it, at volume and to a professional finish. Print can be ordered alongside engraving or for files supplied by the client. See service 07 for the full print spec." },
    { q: "How are projects priced?",
      a: withLinks(
        "Pricing is mostly per bar, scaled by the size of the ensemble. Score and part preparation and notation digitisation are charged per bar at engraving rates; orchestration and arranging per bar at a higher creative rate; and transposition per bar, per instrument. Audio mockups are priced per minute of finished music, and printing and binding per page or item. The estimator combines these and returns an indicative figure for any project.",
        [{ match: /The estimator/g, target: "studio" }]
      ),
      aText: "Pricing is mostly per bar, scaled by the size of the ensemble. Score and part preparation and notation digitisation are charged per bar at engraving rates; orchestration and arranging per bar at a higher creative rate; and transposition per bar, per instrument. Audio mockups are priced per minute of finished music, and printing and binding per page or item. The estimator combines these and returns an indicative figure for any project." },
    { q: "What's the typical turnaround?",
      a: "It really depends on the service, but as a guide: 7–10 working days for chamber-scale work and 2–4 weeks for orchestral. Timelines are set around your project deadline, with review and feedback sessions along the way. Projects marked urgent jump the queue — urgent turnaround brings most work in within 24–48 hours, and if we receive a print request at 10pm for the next day, we deliver. Specific timing is confirmed on quote." },
    { q: "Do you offer a discount for multiple services on the same project?",
      a: withLinks(
        "Yes. Bundle discounts apply when score preparation is paired with audio mockup, or when print and binding is added to a freshly engraved score. The estimator surfaces these automatically.",
        [{ match: /The estimator/g, target: "studio" }]
      ),
      aText: "Yes. Bundle discounts apply when score preparation is paired with audio mockup, or when print and binding is added to a freshly engraved score. The estimator surfaces these automatically." },
    { q: "Can the studio sign an NDA before receiving materials?",
      a: "Yes. NDAs are standard for unpublished commissions, film and theatre projects. Send the document with the brief or request the studio's standard mutual NDA." },
    { q: "Who owns the engraved score and parts?",
      a: "The composer / commissioning party retains all musical copyright. The studio retains craft rights to the typeset layout where applicable. Editable source files are released to the client on request." }
  ];

  // Group: general + per service
  const groups = [
    { id: "general", label: "General", faq: generalFaq },
    ...Object.values(services).map(s => ({ id: s.n, label: `${s.n} — ${s.name}`, faq: s.faq || [] }))
  ].filter(g => g.faq.length > 0);

  // Aggregated JSON-LD for the whole page
  const allEntities = groups.flatMap(g => g.faq.map(f => ({
    "@type": "Question",
    "name": f.q,
    "acceptedAnswer": { "@type": "Answer", "text": f.aText || (typeof f.a === "string" ? f.a : "") }
  })));

  return (
    <div className="page" data-screen-label="06 FAQ">
      <div className="wrap wrap--narrow">

        <div className="svc-crumb">
          <button className="svc-crumb-link" onClick={() => go("home")}>← Home</button>
          <span className="mono-sm svc-crumb-tag">FAQ — FREQUENTLY ASKED</span>
        </div>

        <div className="svc-hero">
          <div className="svc-hero-num mono">FAQ</div>
          <h1 className="svc-hero-title">Frequently asked.</h1>
          <p className="svc-hero-lead">
            Answers to the questions composers, ensembles, publishers and producers most often ask
            before commissioning a project. Jump to a section, or browse all.
          </p>
          <div className="svc-hero-who mono-sm">For — Anyone considering a brief</div>
        </div>

        {/* Section nav */}
        <section className="section faq-toc-wrap">
          <div className="section-head">
            <div className="mono">SECTIONS</div>
            <h2 className="serif">Browse by topic.</h2>
          </div>
          <div className="faq-toc">
            {groups.map(g =>
              <a key={g.id} className="faq-toc-link" href={`#faq-${g.id}`}
                onClick={(e) => { e.preventDefault(); go("faq", `faq-${g.id}`); }}>
                <span className="mono-sm">{g.id === "general" ? "00" : g.id}</span>
                <span>{g.label.replace(/^\d+ — /, "")}</span>
                <span className="faq-toc-count">{g.faq.length}</span>
              </a>
            )}
          </div>
        </section>

        {/* Sections */}
        {groups.map(g =>
          <section key={g.id} id={`faq-${g.id}`} className="section">
            <div className="section-head">
              <div className="mono">{g.id === "general" ? "00" : g.id}</div>
              <h2 className="serif">{g.label.replace(/^\d+ — /, "")}.</h2>
            </div>
            <div className="svc-faq" itemScope itemType="https://schema.org/FAQPage">
              {g.faq.map((f, i) =>
                <details key={i} className="svc-faq-item" itemProp="mainEntity" itemScope itemType="https://schema.org/Question">
                  <summary className="svc-faq-q">
                    <span className="svc-faq-num mono-sm">{String(i + 1).padStart(2, "0")}</span>
                    <span itemProp="name">{f.q}</span>
                    <span className="svc-faq-mark" aria-hidden="true">+</span>
                  </summary>
                  <div className="svc-faq-a" itemProp="acceptedAnswer" itemScope itemType="https://schema.org/Answer">
                    <p itemProp="text">{autoLinkV2(f.a)}</p>
                  </div>
                </details>
              )}
            </div>
            {g.id !== "general" &&
              <div style={{ marginTop: 24 }}>
                <button
                  className="svc-step-link"
                  style={{ background: "none", border: "none", padding: 0, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", cursor: "pointer" }}
                  onClick={() => go(`service:${g.id}`)}
                >Full service page → {g.label.replace(/^\d+ — /, "")}</button>
              </div>
            }
          </section>
        )}

        {/* CTA */}
        <section className="section" style={{ borderBottom: "none" }}>
          <div className="svc-cta">
            <div>
              <div className="mono" style={{ marginBottom: 12 }}>STILL UNSURE</div>
              <h2 className="svc-cta-title">
                Talk to the studio<br />
                <span style={{ color: "var(--fg-muted)" }}>about your project.</span>
              </h2>
            </div>
            <div className="svc-cta-actions">
              <button className="btn-primary" onClick={() => go("submit")}>
                <span>Submit a brief</span>
                <span className="arrow"></span>
              </button>
              <button className="btn-secondary" onClick={() => go("studio", "estimator")}>Use the estimator →</button>
            </div>
          </div>
        </section>

        <SiteFooter go={go} />
      </div>

      {/* Aggregated JSON-LD for SEO */}
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": allEntities
      }) }} />
    </div>
  );
}

window.FAQPage = FAQPage;
