const { useState: useStateLR } = React;

const LINE_METHODS = [
  {
    id: "leak-detection",
    name: "Water line leak detection",
    best: "Best when the meter is spinning, pressure drops, or the yard stays wet.",
    check: "Meter test, pressure test, acoustic locate, and photos before digging.",
    concern: "Avoids digging the wrong spot."
  },
  {
    id: "water-spot",
    name: "Water line spot repair",
    best: "Best when one section is damaged and the rest of the line looks healthy.",
    check: "Locate the failed section, expose only what is needed, then pressure test.",
    concern: "Fixes the known failure without selling a whole line by default."
  },
  {
    id: "water-replace",
    name: "Water line replacement",
    best: "Best when the line has repeated leaks, old material, or long-term failure risk.",
    check: "Line path, material, utility marks, yard access, and shutoff plan.",
    concern: "Solves repeat water outages instead of paying for the same leak twice."
  },
  {
    id: "camera",
    name: "Sewer camera inspection",
    best: "Best after repeated clogs, roots, odor, or backups.",
    check: "Camera footage, depth, distance, pipe material, roots, bellies, cracks, and collapse.",
    concern: "You see the evidence before any big repair is recommended."
  },
  {
    id: "sewer-point",
    name: "Sewer line point repair",
    best: "Best when damage is limited to one area and the rest of the run is usable.",
    check: "Camera footage, locate marks, depth, access, and utility marking.",
    concern: "Targets the bad section instead of opening the whole yard."
  },
  {
    id: "cipp",
    name: "HammerHead Bluelight CIPP",
    best: "Best when the pipe still has a usable path but needs a new liner inside.",
    check: "Cleanout access, pipe shape, active infiltration, collapse risk, and camera footage.",
    concern: "Creates a pipe-within-a-pipe with less digging when the host pipe qualifies."
  },
  {
    id: "pb30",
    name: "HammerHead PortaBurst PB30",
    best: "Best when the old sewer is too damaged for lining but the path can be reused.",
    check: "Access pits, line path, depth, utilities, soil conditions, and replacement pipe plan.",
    concern: "Pulls a new line through the old path instead of trenching every foot."
  },
  {
    id: "sewer-replace",
    name: "Full sewer line replacement",
    best: "Best when the line is collapsed, badly bellied, misgraded, or too damaged for trenchless.",
    check: "Camera evidence, grade, depth, access, utilities, permits, and restoration plan.",
    concern: "Gives a permanent reset when repair would only delay the real failure."
  }
];

const LINE_CASES = [
  {
    id: "wet-yard",
    kind: "water",
    label: "Wet yard or meter spinning",
    service: "Water Line Leak Detection",
    urgency: "P2",
    score: 84,
    dot: "yard",
    headline: "Find the leak before anyone guesses with a shovel.",
    plain: "This usually starts with leak detection. If the rest of the water line is healthy, a spot repair may be enough. If the line has repeat failures, replacement can be cheaper long-term.",
    likely: "Likely options to discuss: leak detection, water line spot repair, or water line replacement.",
    firstMove: "Confirm the leak, mark the location, then price the smallest repair that actually solves it.",
    tools: ["leak-detection", "water-spot", "water-replace"],
    step: 1
  },
  {
    id: "low-pressure",
    kind: "water",
    label: "Low pressure or no water",
    service: "Water Line Diagnostic",
    urgency: "P2",
    score: 72,
    dot: "street",
    headline: "Separate a house problem from a main-line problem.",
    plain: "Low pressure can be a fixture issue, valve issue, pressure regulator, or a failing water service line. The advantage is proving where the loss is before recommending a large repair.",
    likely: "Likely options to discuss: pressure diagnostic, leak detection, water line repair, or replacement.",
    firstMove: "Check pressure at the right points, inspect shutoffs, and test whether the service line is losing water.",
    tools: ["leak-detection", "water-spot", "water-replace"],
    step: 1
  },
  {
    id: "repeat-clog",
    kind: "sewer",
    label: "Drain clog keeps coming back",
    service: "Sewer Camera + Drain Service",
    urgency: "P3",
    score: 68,
    dot: "home",
    headline: "Do not pay for the same clog again without seeing the pipe.",
    plain: "A drain cleaning may solve it today, but a repeat clog needs a camera. Roots, bellies, cracks, offsets, grease, and old pipe each point to a different fix.",
    likely: "Likely options to discuss: drain cleaning, camera inspection, sewer point repair, Bluelight CIPP, or PB30.",
    firstMove: "Clear the line enough to run a camera, then show the homeowner the actual cause.",
    tools: ["camera", "sewer-point", "cipp", "pb30"],
    step: 0
  },
  {
    id: "roots-cracks",
    kind: "sewer",
    label: "Roots, cracks, or old clay",
    service: "Sewer Line Repair Options",
    urgency: "P2",
    score: 86,
    dot: "yard",
    headline: "Match the repair to the damaged section instead of tearing up everything.",
    plain: "Roots and cracks can sometimes be handled with a point repair or CIPP. If the pipe is crushed or the grade is wrong, pipe bursting or replacement may be the better long-term move.",
    likely: "Likely options to discuss: sewer point repair, HammerHead Bluelight CIPP, PB30, or full replacement.",
    firstMove: "Camera the whole run, locate the damage, then compare repair, lining, bursting, and excavation honestly.",
    tools: ["camera", "sewer-point", "cipp", "pb30", "sewer-replace"],
    step: 1
  },
  {
    id: "under-driveway",
    kind: "sewer",
    label: "Line under driveway or landscaping",
    service: "Trenchless Sewer Repair Review",
    urgency: "P2",
    score: 91,
    dot: "driveway",
    headline: "This is where less-dig options can protect the expensive stuff.",
    plain: "When a sewer line runs under concrete, patios, landscaping, or a long yard, CIPP or PB30 can be a strong option if the camera shows the pipe qualifies.",
    likely: "Likely options to discuss: Bluelight CIPP, PortaBurst PB30, sewer point repair, or replacement plan.",
    firstMove: "Scope, locate, measure, and decide whether lining or bursting can avoid a full trench.",
    tools: ["camera", "cipp", "pb30", "sewer-point"],
    step: 2
  },
  {
    id: "collapse",
    kind: "sewer",
    label: "Collapsed sewer or sewage backup",
    service: "Emergency Sewer Line Diagnostic",
    urgency: "P1",
    score: 95,
    dot: "street",
    headline: "Stop the backup, then show the repair path clearly.",
    plain: "A collapse or active sewage backup is urgent. The goal is to stabilize the home, document the failure, then compare point repair, PB30, or full replacement depending on the break.",
    likely: "Likely options to discuss: emergency drain service, camera, sewer point repair, PB30, or full sewer replacement.",
    firstMove: "Open the line if possible, run camera evidence, mark the failure, and explain downtime before work starts.",
    tools: ["camera", "sewer-point", "pb30", "sewer-replace"],
    step: 2
  }
];

const LINE_YARD_PROOF = [
  {
    id: "dig",
    label: "Traditional dig",
    title: "Full trench disruption",
    stat: "Most invasive",
    copy: "When excavation is the only right answer, the yard, driveway path, or landscaping can take the hit. That is why we prove the pipe first.",
    img: "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Pipeline_Trench_Excavation.jpg/960px-Pipeline_Trench_Excavation.jpg",
    alt: "Open trench excavation example showing a long dug path through the ground",
    source: "Example photo: Sabino Freitas Correa / CC BY-SA 4.0",
    sourceUrl: "https://commons.wikimedia.org/wiki/File:Pipeline_Trench_Excavation.jpg"
  },
  {
    id: "pb30",
    label: "PortaBurst PB30",
    title: "New pipe, less yard damage",
    stat: "Small access pits",
    copy: "PB30 can pull a new sewer line through the old path when the line qualifies, helping avoid a full trench across the lawn.",
    img: "https://i.ytimg.com/vi/wOoW1si4G3M/hqdefault.jpg",
    alt: "Official HammerHead PortaBurst PB30 pipe bursting video still",
    source: "Official HammerHead video still",
    sourceUrl: "https://www.youtube.com/watch?v=wOoW1si4G3M"
  },
  {
    id: "cipp",
    label: "Bluelight CIPP",
    title: "Pipe-within-a-pipe",
    stat: "Line inside the line",
    copy: "Bluelight CIPP can renew the inside of the pipe when the host pipe still has a usable path, saving more of the yard when conditions are right.",
    img: "https://i.ytimg.com/vi/5fWqmyst8Mg/hqdefault.jpg",
    alt: "Official HammerHead Bluelight LED CIPP system video still",
    source: "Official HammerHead video still",
    sourceUrl: "https://www.youtube.com/watch?v=5fWqmyst8Mg"
  }
];

function LineRescue({ onBook }) {
  const brand = window.CB_DATA.brand;
  const [activeId, setActiveId] = useStateLR("repeat-clog");
  const [detailId, setDetailId] = useStateLR("camera");
  const active = LINE_CASES.find(c => c.id === activeId) || LINE_CASES[0];
  const activeTools = LINE_METHODS.filter(m => active.tools.includes(m.id));
  const detail = LINE_METHODS.find(m => m.id === detailId && active.tools.includes(m.id)) || activeTools[0];

  const selectCase = (id) => {
    const next = LINE_CASES.find(c => c.id === id);
    setActiveId(id);
    if (next && !next.tools.includes(detailId)) setDetailId(next.tools[0]);
  };

  const book = () => {
    if (!onBook) return;
    onBook({
      problem: "line-rescue",
      presetService: active.service,
      serviceCode: active.kind === "water" ? "WLN-09" : "SWR-04",
      notes: `Underground Line Rescue: ${active.label}. ${active.likely} First move: ${active.firstMove}`
    });
  };

  const bookSecondOpinion = () => {
    if (!onBook) return;
    onBook({
      problem: "second-opinion",
      presetService: "Second Opinion Before You Dig",
      serviceCode: "2ND",
      notes: `Second Opinion Before You Dig: review a sewer or water line replacement quote against camera/leak locate evidence. Customer concern: ${active.label}.`
    });
  };

  return (
    <section className="lr" id="line-rescue" data-screen-label="line-rescue">
      <div className="lr-ticker" aria-hidden="true">
        <div className="lr-ticker-track">
          {["WATER LINE LEAK DETECTION", "SPOT REPAIR", "WATER LINE REPLACEMENT", "SEWER POINT REPAIR", "HAMMERHEAD BLUELIGHT CIPP", "PORTABURST PB30", "DRAIN CAMERA", "LOCAL CENTRAL KY CREWS", "WATER LINE LEAK DETECTION", "SPOT REPAIR", "WATER LINE REPLACEMENT", "SEWER POINT REPAIR", "HAMMERHEAD BLUELIGHT CIPP", "PORTABURST PB30", "DRAIN CAMERA", "LOCAL CENTRAL KY CREWS"].map((item, i) => (
            <span key={i}>{item}</span>
          ))}
        </div>
      </div>

      <div className="container lr-inner">
        <div className="lr-head">
          <div>
            <div className="lr-eyebrow"><span /> UNDERGROUND LINE RESCUE</div>
            <h2>Repair what makes sense. Replace only when the pipe proves it.</h2>
          </div>
          <p>
            Water line leaks, recurring drain clogs, sewer failures, CIPP lining, PB30 pipe bursting, and replacements - handled with evidence first. We show the camera footage, leak location, photos, and plain-English options before anyone talks big money.
          </p>
        </div>

        <div className="lr-trust-strip" aria-label="Line service promises">
          <div><strong>01</strong><span>Diagnose first</span></div>
          <div><strong>02</strong><span>Show the evidence</span></div>
          <div><strong>03</strong><span>Compare repair vs replacement</span></div>
          <div><strong>04</strong><span>Dig less when possible</span></div>
        </div>

        <div className="lr-second-opinion">
          <div>
            <span>QUOTED A FULL REPLACEMENT?</span>
            <strong>Before the yard gets opened, let us prove what the pipe actually needs.</strong>
            <p>We compare the quote against camera footage, leak location, access, pipe condition, and trenchless eligibility.</p>
          </div>
          <button type="button" onClick={bookSecondOpinion}>Second opinion before you dig</button>
        </div>

        <div className="lr-workbench">
          <div className="lr-picker" aria-label="Choose your line problem">
            <div className="lr-panel-label">WHAT ARE YOU SEEING?</div>
            {LINE_CASES.map(item => (
              <button
                key={item.id}
                className={`lr-case ${active.id === item.id ? "is-active" : ""}`}
                type="button"
                onClick={() => selectCase(item.id)}>
                <span className={`lr-case-type ${item.kind}`}>{item.kind}</span>
                <strong>{item.label}</strong>
                <small>{item.service}</small>
              </button>
            ))}
          </div>

          <div className="lr-output" aria-live="polite">
            <div className="lr-ticket-head">
              <div>
                <span>LINE READ</span>
                <strong>{active.service}</strong>
              </div>
              <div className={`lr-priority ${active.urgency.toLowerCase()}`}>{active.urgency === 'P1' ? 'URGENT' : active.urgency === 'P2' ? 'SOON' : 'PLANNED'}</div>
            </div>

            <div className={`lr-map ${active.kind}`}>
              <div className="lr-map-label house">HOUSE</div>
              <div className="lr-map-label yard">YARD</div>
              <div className="lr-map-label street">STREET</div>
              <div className="lr-grade" />
              <div className="lr-pipe lr-pipe-water" />
              <div className="lr-pipe lr-pipe-sewer" />
              <div className={`lr-problem-dot ${active.dot}`}>
                <span>{active.kind === "water" ? "LEAK" : "FAULT"}</span>
              </div>
              <div className="lr-scan" />
            </div>

            <div className="lr-result-grid">
              <div className="lr-result-main">
                <span className="lr-mini-label">LIKELY OPTIONS TO DISCUSS</span>
                <h3>{active.headline}</h3>
                <p>{active.plain}</p>
              </div>
              <div className="lr-score">
                <span>FIT</span>
                <strong>{active.score >= 85 ? 'STRONG' : active.score >= 70 ? 'GOOD' : 'REVIEW'}</strong>
                <small>{active.kind === "sewer" ? "camera needed" : "locate first"}</small>
              </div>
            </div>

            <div className="lr-ladder" aria-label="Repair versus replacement path">
              {["Clear or locate", "Targeted repair", "Permanent rebuild"].map((step, i) => (
                <div key={step} className={`lr-ladder-step ${i <= active.step ? "is-on" : ""}`}>
                  <span>{String(i + 1).padStart(2, "0")}</span>
                  <strong>{step}</strong>
                </div>
              ))}
            </div>

            <div className="lr-tools-row">
              {activeTools.map(tool => (
                <button
                  key={tool.id}
                  className={`lr-tool-chip ${detail.id === tool.id ? "is-active" : ""}`}
                  type="button"
                  onClick={() => setDetailId(tool.id)}>
                  {tool.name}
                </button>
              ))}
            </div>

            {detail && (
              <div className="lr-method">
                <div>
                  <span className="lr-mini-label">BEST WHEN</span>
                  <p>{detail.best}</p>
                </div>
                <div>
                  <span className="lr-mini-label">WHAT WE CHECK FIRST</span>
                  <p>{detail.check}</p>
                </div>
                <div>
                  <span className="lr-mini-label">HOMEOWNER WIN</span>
                  <p>{detail.concern}</p>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="lr-yard-save" aria-label="Traditional digging compared with PB30 and CIPP lawn-saving options">
          <div className="lr-yard-copy">
            <span>THE YARD-SAVER CONVERSATION</span>
            <h3>Show them the damage they are trying to avoid.</h3>
            <p>Some lines need digging. But when PB30 pipe bursting or Bluelight CIPP fits, the customer should see why those options can protect the lawn, driveway, and landscaping.</p>
          </div>
          <div className="lr-yard-grid">
            {LINE_YARD_PROOF.map(item => (
              <article className={`lr-yard-card ${item.id}`} key={item.id}>
                <div className="lr-yard-media">
                  <img src={item.img} alt={item.alt} loading="lazy" referrerPolicy="no-referrer" />
                  <div className="lr-yard-badge">{item.stat}</div>
                </div>
                <div className="lr-yard-body">
                  <span>{item.label}</span>
                  <h4>{item.title}</h4>
                  <p>{item.copy}</p>
                  <a href={item.sourceUrl} target="_blank" rel="noopener noreferrer">{item.source}</a>
                </div>
              </article>
            ))}
          </div>
          <div className="lr-yard-note">
            <strong>Honest rule:</strong> trenchless is an option only after camera/locate confirms the pipe qualifies. If full replacement is smarter, we say that too.
          </div>
        </div>

        <div className="lr-bottom">
          <div className="lr-objections">
            {[
              ["Can you repair one section?", "Yes, when the camera or leak locate proves the rest of the line is worth saving."],
              ["Will my yard be destroyed?", "Not if the line qualifies for a smaller dig, CIPP, or PB30. We check before recommending it."],
              ["How do I know I need it?", "You should see footage, locate marks, photos, and a clear repair-vs-replace explanation first."],
              ["Who handles utility marking?", "We plan access, safety, utility marking, permits, downtime, and restoration before the work starts."]
            ].map(([q, a]) => (
              <div className="lr-objection" key={q}>
                <strong>{q}</strong>
                <p>{a}</p>
              </div>
            ))}
          </div>

          <div className="lr-cta-panel">
            <span>NOT SURE IF REPAIR IS ENOUGH?</span>
            <h3>Get a line diagnosis before you dig.</h3>
            <p>Local Central Kentucky crews. Camera, leak location, repair options, replacement options, and straight talk.</p>
            <div className="lr-cta-actions">
              <button className="lr-primary" type="button" onClick={book}>Get a line diagnosis</button>
              <a className="lr-phone" href={`tel:${brand.phoneRaw}`}>Call {brand.phone}</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.LineRescue = LineRescue;
