// PAR GROUP — Work Index (new), Case Study, Compare, Stats, Process

const { useState: useStateM, useEffect: useEffectM, useRef: useRefM, useCallback: useCallbackM } = React;

// ─── Work Index (NEW) ──────────────────────────────────────────────────────

function WorkIndex() {
  const ref = useReveal();
  const projects = [
    {
      ref: 'PAR/24-014',
      title: 'Three-storey Victorian rebuild',
      loc: 'Balham, SW12',
      year: '2024',
      img: window.__resources.imgGrandSteelBeam,
      ribbon: 'Featured',
      scope: ['Basement', 'Steel', 'Loft', 'Rear ext.'],
    },
    {
      ref: 'PAR/24-009',
      title: 'Open-plan ground-floor & side return',
      loc: 'Highbury, N5',
      year: '2024',
      img: window.__resources.imgFloorFrame,
      ribbon: 'Recent',
      scope: ['Steel', 'Side return', 'LB removal'],
    },
    {
      ref: 'PAR/24-002',
      title: 'Mansard loft + steel floor plate',
      loc: 'Clapham, SW4',
      year: '2024',
      img: window.__resources.imgLoftBrickwork,
      ribbon: 'Recent',
      scope: ['Loft', 'Mansard', 'Steel'],
    },
    {
      ref: 'PAR/23-021',
      title: 'Full basement dig & underpin',
      loc: 'Wandsworth, SW18',
      year: '2023',
      img: window.__resources.imgBricksFoundations,
      ribbon: 'Archive',
      scope: ['Basement', 'Underpin', 'Tanking'],
    },
    {
      ref: 'PAR/23-014',
      title: 'Double-storey wrap-around extension',
      loc: 'Forest Hill, SE23',
      year: '2023',
      img: window.__resources.imgRearExtensionSide,
      ribbon: 'Archive',
      scope: ['Rear ext.', 'Wrap-around', 'Steel'],
    },
    {
      ref: 'PAR/23-007',
      title: 'Portal-frame goalpost opening',
      loc: 'Bermondsey, SE16',
      year: '2023',
      img: window.__resources.imgBeamsOverhead,
      ribbon: 'Archive',
      scope: ['Steel', 'Portal frame', 'LB removal'],
    },
  ];

  return (
    <section className="section" id="projects" ref={ref}>
      <div className="container">
        <div className="section-head reveal">
          <div className="section-id">
            <span className="mono">— Section 02 · Selected work</span>
          </div>
          <h2 className="section-title">
            Six recent jobs. <em>Steel still warm.</em>
          </h2>
        </div>

        <div className="work-index reveal">
          {projects.map((p) => (
            <a href="#case" className="work-card" key={p.ref}>
              <div className="ph">
                <img src={p.img} alt={p.title} loading="lazy" />
                <span className="ribbon">{p.ribbon}</span>
                <span className="ref">{p.ref}</span>
              </div>
              <div className="meta">
                <h4>{p.title}</h4>
                <div className="row">
                  <span className="k">Location</span>
                  <span className="v">{p.loc}</span>
                </div>
                <div className="row">
                  <span className="k">Year</span>
                  <span className="v">{p.year}</span>
                </div>
                <div className="scope">
                  {p.scope.map((s) => <span key={s}>{s}</span>)}
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Case study (kept, slightly tightened) ─────────────────────────────────

function CaseStudy({ onPhoto }) {
  const ref = useReveal();
  const photos = [
    { src: window.__resources.imgGrandSteelBeam,     cls: 'span-7', tag: 'Phase 03 · Primary steel installed' },
    { src: window.__resources.imgStripOutBay,        cls: 'span-5', tag: 'Phase 01 · Strip out to brick' },
    { src: window.__resources.imgFloorFrame,         cls: 'span-8', tag: 'Phase 04 · New first-floor framing' },
    { src: window.__resources.imgLoftBrickwork,      cls: 'span-4', tag: 'Phase 05 · Loft enclosure' },
    { src: window.__resources.imgBeamsOverhead,      cls: 'span-6', tag: 'Phase 03 · Red oxide steels overhead' },
    { src: window.__resources.imgBricksFoundations,  cls: 'span-6', tag: 'Phase 02 · Rear underpinning & brick' },
  ];
  return (
    <section className="section" id="case" style={{ background: 'var(--bg-2)' }} ref={ref}>
      <div className="container">
        <div className="section-head reveal">
          <div className="section-id">
            <span className="mono">— Featured project · PAR/24-05</span>
          </div>
          <h2 className="section-title">
            A Victorian terrace, taken back to bricks &mdash; then put back <em>better.</em>
          </h2>
        </div>

        <div className="case-id-strip reveal">
          <div className="item"><span className="mono">Project</span><span className="v">PAR/24-05</span></div>
          <div className="item"><span className="mono">Location</span><span className="v">Balham, SW12</span></div>
          <div className="item"><span className="mono">Property</span><span className="v">3-storey Victorian terrace</span></div>
          <div className="item"><span className="mono">Programme</span><span className="v">12 months</span></div>
          <div className="item"><span className="mono">Scope</span><span className="v">Structure · Basement · Loft</span></div>
          <div className="item"><span className="mono">Steel</span><span className="v">12 tonnes</span></div>
          <div className="item"><span className="mono">Spoil</span><span className="v">100 m³ excavated</span></div>
          <div className="item"><span className="mono">Status</span><span className="v" style={{color:'var(--accent)'}}>Complete</span></div>
        </div>

        <div className="case-narrative reveal">
          <div className="col">
            <h3 className="h-large">Gutted, deepened, raised.</h3>
          </div>
          <div className="col">
            <p className="body" style={{ fontSize: 17 }}>
              The brief: take a tired three-storey Victorian terrace and bring it
              forward by a hundred years &mdash; without losing the brick shell. Every
              internal wall came out. The basement was excavated and underpinned
              for full head-height. New steels carried the load across open-plan
              ground and first floors. The loft was opened up with a rear dormer
              and stitched into a new floor structure.
            </p>
            <p className="body" style={{ fontSize: 17 }}>
              Twelve tonnes of structural steel, a hundred cubic metres of spoil
              excavated, and a programme delivered against a fixed sign-off date.
              One team, one contract, one phone call.
            </p>
          </div>
        </div>

        <div className="case-photos">
          {photos.map((p, i) => (
            <div className={'case-photo ' + p.cls} key={i} onClick={() => onPhoto(i)}>
              <img src={p.src} alt={p.tag} loading="lazy" />
              <span className="tag">{p.tag}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Compare slider (drag to reveal) ───────────────────────────────────────

function Compare() {
  const [pos, setPos] = useStateM(50);
  const wrap = useRefM(null);
  const dragging = useRefM(false);

  const onMove = useCallbackM((clientX) => {
    if (!wrap.current) return;
    const rect = wrap.current.getBoundingClientRect();
    const p = ((clientX - rect.left) / rect.width) * 100;
    setPos(Math.max(0, Math.min(100, p)));
  }, []);

  useEffectM(() => {
    const move = (e) => { if (dragging.current) onMove(e.clientX); };
    const tmove = (e) => { if (dragging.current && e.touches[0]) onMove(e.touches[0].clientX); };
    const stop = () => dragging.current = false;
    window.addEventListener('mousemove', move);
    window.addEventListener('touchmove', tmove);
    window.addEventListener('mouseup', stop);
    window.addEventListener('touchend', stop);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('touchmove', tmove);
      window.removeEventListener('mouseup', stop);
      window.removeEventListener('touchend', stop);
    };
  }, [onMove]);

  return (
    <section className="section" style={{ paddingTop: 0, background: 'var(--bg-2)' }}>
      <div className="container">
        <div className="reveal" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
          <span className="mono">— Drag to compare · existing → structure in</span>
          <span className="mono" style={{ color: 'var(--fg-3)' }}>↔ {Math.round(pos)}%</span>
        </div>
        <div className="compare reveal" ref={wrap}
             onMouseDown={(e) => { dragging.current = true; onMove(e.clientX); }}
             onTouchStart={(e) => { dragging.current = true; if (e.touches[0]) onMove(e.touches[0].clientX); }}>
          <img src={window.__resources.imgBricksFoundations} alt="Before — stripped" />
          <div className="clip" style={{ clipPath: `inset(0 ${100 - pos}% 0 0)` }}>
            <img src={window.__resources.imgRearExtensionSide} alt="After — steel installed" />
          </div>
          <div className="label l">Strip-out</div>
          <div className="label r">Steel in</div>
          <div className="handle" style={{ left: `${pos}%` }}></div>
          <div className="knob" style={{ left: `${pos}%`, top: '50%' }}>↔</div>
        </div>
      </div>
    </section>
  );
}

// ─── Stats (refined with bar fills) ────────────────────────────────────────

function Stats() {
  const ref = useRefM(null);
  // Always trigger counter on mount — IntersectionObserver is unreliable
  // in certain embed contexts; the count-up is small and runs once.
  const a = useCountUp(12, 1500, true);
  const b = useCountUp(48, 1700, true);
  const c = useCountUp(820, 1900, true);
  const d = useCountUp(100, 1500, true);
  useEffectM(() => {
    if (ref.current) ref.current.querySelectorAll('.stat').forEach(s => s.classList.add('in'));
  }, []);
  return (
    <section ref={ref}>
      <div className="stats">
        <div className="stat" style={{ '--pct': 0.60 }}>
          <div className="v">{a}<span className="unit">yrs</span></div>
          <div className="mono l">Years building London</div>
          <div className="bar-track"><div className="bar-fill" /></div>
        </div>
        <div className="stat" style={{ '--pct': 0.80 }}>
          <div className="v">{b}<span className="unit">+</span></div>
          <div className="mono l">Structural projects delivered</div>
          <div className="bar-track"><div className="bar-fill" /></div>
        </div>
        <div className="stat" style={{ '--pct': 0.95 }}>
          <div className="v">{c}<span className="unit">t</span></div>
          <div className="mono l">Steel framed & installed</div>
          <div className="bar-track"><div className="bar-fill" /></div>
        </div>
        <div className="stat" style={{ '--pct': 1.00 }}>
          <div className="v">{d}<span className="unit">%</span></div>
          <div className="mono l">Building Control sign-off, first pass</div>
          <div className="bar-track"><div className="bar-fill" /></div>
        </div>
      </div>
    </section>
  );
}

// ─── Process (interactive timeline) ────────────────────────────────────────

function Process() {
  const ref = useReveal();
  const steps = [
    {
      n: '01', t: 'Site visit & survey',
      d: 'We walk the property with you, measure up, and talk through what is structurally possible. No charge, no obligation. A trained eye will spot what the photos miss — chimney stacks bearing on lintels, undersized footings, the wall you thought was a partition that is actually holding the roof up.',
      checks: ['Walked-through brief', 'No obligation', 'Same-week turnaround'],
      img: window.__resources.imgStripOutBay,
      stamp: 'Phase 01 · Survey on the ground',
    },
    {
      n: '02', t: 'Engineering & quote',
      d: 'We coordinate with your architect and structural engineer, then return a fixed-price quote with a phased programme. Everything we build is signed off on paper before a brick moves.',
      checks: ['Architect collaboration', 'Structural engineer coordination', 'Fixed-price quote', 'Phased programme'],
      img: window.__resources.imgBricksFoundations,
      stamp: 'Phase 02 · Drawings, calcs, programme',
    },
    {
      n: '03', t: 'Groundworks & steel',
      d: 'Underpinning, foundations and the steel frame go in first. Building Control inspect at every key stage. Temporary propping holds the shell while we work the structure in below and across.',
      checks: ['Underpinning', 'Foundations', 'Primary steel install', 'Building Control hold-points'],
      img: window.__resources.imgGrandSteelBeam,
      stamp: 'Phase 03 · Steel & substructure',
    },
    {
      n: '04', t: 'Build out',
      d: 'New floors, walls, roof, openings. Programmed week-by-week so trades flow on cleanly behind us — first-fix electrical, plumbing and joinery onto a structure that is square, level and dry.',
      checks: ['New floor framing', 'External envelope', 'Trades coordination', 'Weekly programme'],
      img: window.__resources.imgFloorFrame,
      stamp: 'Phase 04 · Build out',
    },
    {
      n: '05', t: 'Handover',
      d: 'Final inspection, sign-off paperwork, a clean site, and a 10-year structural workmanship warranty for the work we put in. We do not leave until you would let us back in.',
      checks: ['Building Control sign-off', 'Clean handover', '10yr structural warranty', 'Snag-list closed'],
      img: window.__resources.imgLoftBrickwork,
      stamp: 'Phase 05 · Handover',
    },
  ];
  const [idx, setIdx] = useStateM(0);
  const cur = steps[idx];
  return (
    <section className="section" id="process" ref={ref}>
      <div className="container">
        <div className="section-head reveal">
          <div className="section-id">
            <span className="mono">— Section 03 · How we work</span>
          </div>
          <h2 className="section-title">
            Five stages. <em>No surprises.</em>
          </h2>
        </div>

        <div className="process-wrap reveal">
          <div className="process-tabs" role="tablist">
            {steps.map((s, i) => (
              <button
                key={s.n}
                role="tab"
                aria-selected={i === idx}
                className={'process-tab' + (i === idx ? ' active' : '')}
                onClick={() => setIdx(i)}>
                <span className="phase">Phase {s.n}</span>
                <span className="num">{s.n}</span>
                <span className="lbl">{s.t}</span>
              </button>
            ))}
          </div>

          <div className="process-detail">
            <div className="pd-vis">
              <img key={cur.n} src={cur.img} alt={cur.t} />
              <span className="stamp">{cur.stamp}</span>
            </div>
            <div className="pd-text">
              <span className="mono" style={{ color: 'var(--fg-3)' }}>Phase {cur.n} / 05</span>
              <h3 className="h-large">{cur.t}</h3>
              <p>{cur.d}</p>
              <ul className="pd-checks">
                {cur.checks.map((c) => <li key={c}>{c}</li>)}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { WorkIndex, CaseStudy, Compare, Stats, Process });
