// 施工事例 一覧 + 詳細

const SC = window.Site;
const { T: TC, COMPANY: COC, CASES: CASESC, CoverImg: ImgC, Icon: IcC, SectionHeading: SHC, Page: PageC, PageHero: HeroC, siteHref: hrefC, siteCaseHref: caseHrefC, caseNumberLabel: caseNumberC, hasText: hasTextC, hasImageRef: hasImageRefC } = SC;

const CATS = ['すべて'].concat(CASESC.map((c) => c.cat).filter((cat, i, arr) => cat && arr.indexOf(cat) === i));
const currentCaseCat = () => new URLSearchParams(window.location.search).get('cat') || 'すべて';
const caseCatHref = (cat) => cat === 'すべて' ? hrefC('cases') : `${hrefC('cases')}&cat=${encodeURIComponent(cat)}`;
const currentCase = () => {
  const caseId = new URLSearchParams(window.location.search).get('case');
  return CASESC.find((c) => c.id === caseId) || CASESC[0];
};

// ---------------- Cases Index ----------------
function PageCasesIndex() {
  const activeCat = currentCaseCat();
  const visibleCases = activeCat === 'すべて' ? CASESC : CASESC.filter((c) => c.cat === activeCat);
  return (
    <PageC active="cases">
      <HeroC num="02" en="WORKS" title="施工事例" lead={`${COC.area}で対応させていただいた事例の一部をご紹介します。所在地・築年数・工期は、実際の事例をもとに、ご家庭が特定されないよう一部表記を調整してご紹介しています。`} />
      {/* filter bar */}
      <section style={{ background: '#fff', padding: '24px 56px', borderBottom: `1px solid ${TC.line}` }}>
        <div style={{ display: 'flex', gap: 0, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 11, color: TC.green, letterSpacing: 3, marginRight: 18, fontWeight: 700 }}>FILTER</div>
          {CATS.map((c) => {
            const active = activeCat === c;
            return (
              <a key={c} href={caseCatHref(c)} style={{
                padding: '8px 18px', fontSize: 13.5, fontFamily: '"Noto Sans JP", sans-serif', fontWeight: 600,
                color: active ? '#fff' : TC.ink,
                background: active ? TC.green : 'transparent',
                borderRadius: 999, marginRight: 8,
                textDecoration: 'none',
              }}>{c}</a>
            );
          })}
        </div>
      </section>

      <section style={{ background: TC.paper, padding: '60px 56px 88px' }}>
        {visibleCases.length ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
            {visibleCases.map((c) => (
              <a key={c.id} href={caseHrefC(c.id)} style={{ background: '#fff', borderRadius: 6, overflow: 'hidden', display: 'block', textDecoration: 'none' }}>
                <div style={{ position: 'relative' }}>
                  <ImgC src={c.photo || c.after} ratio="4/3" alt={`${c.work}（${c.cat}）の施工写真`} />
                  <span style={{ position: 'absolute', top: 12, left: 12, background: TC.greenSoft, color: TC.greenInk, fontSize: 11, fontWeight: 700, padding: '4px 10px', borderRadius: 999 }}>
                    {c.cat}
                  </span>
                </div>
                <div style={{ padding: '18px 20px 22px' }}>
                  {caseNumberC(c.id) && (
                    <div style={{ fontSize: 11, color: TC.ink50, fontWeight: 700, letterSpacing: 1.5, marginBottom: 8 }}>{caseNumberC(c.id)}</div>
                  )}
                  <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 17, fontWeight: 700, color: TC.ink, lineHeight: 1.5, marginBottom: 10 }}>{c.work}</div>
                  <div style={{ fontSize: 12, color: TC.ink70, lineHeight: 1.8, display: 'flex', justifyContent: 'space-between' }}>
                    <span>{c.area}</span><span>{c.term}</span>
                  </div>
                </div>
              </a>
            ))}
          </div>
        ) : (
          <div style={{ background: '#fff', border: `1px solid ${TC.line}`, borderRadius: 6, padding: '28px 32px', textAlign: 'center' }}>
            <p style={{ margin: '0 0 14px', color: TC.ink70, fontSize: 15, lineHeight: 1.9 }}>このカテゴリの事例は現在準備中です。「すべて」から他の事例をご覧ください。</p>
            <a href={hrefC('cases')} style={{ color: TC.orangeDeep, fontSize: 13.5, fontWeight: 700, textDecoration: 'none', borderBottom: `1.5px solid ${TC.orangeDeep}`, paddingBottom: 3 }}>すべての事例を見る</a>
          </div>
        )}
      </section>
    </PageC>
  );
}

// ---------------- Cases Detail ----------------
function PageCaseDetail() {
  const c = currentCase();
  const numberLabel = caseNumberC(c.id);
  const fallbackFlow = [
    { ph: SC.ASSETS.heroWide1, t: '現地確認', d: '屋根に上がって状況を確認し、雨水の経路となりうる場所を見ていきました。' },
    { ph: SC.ASSETS.case2,     t: '施工',     d: '合意した範囲を施工。進捗は撮影しながらお伝えしました。' },
    { ph: SC.ASSETS.case1,     t: '完工確認', d: '完工後にご一緒に確認いただきました。' },
  ];
  const rawFlow = Object.prototype.hasOwnProperty.call(c, 'flow') ? c.flow : fallbackFlow;
  const flow = Array.isArray(rawFlow) ? rawFlow.filter((x) => x && (hasTextC(x.t) || hasTextC(x.d) || hasImageRefC(x.ph))) : [];
  const relatedSectionNumber = flow.length > 0 ? '04' : '03';
  return (
    <PageC active="cases">
      <section style={{ background: TC.paper, padding: '40px 56px 0' }}>
        <SC.Breadcrumb items={['ホーム', '施工事例', numberLabel || c.work]} />
      </section>
      <section style={{ background: TC.paper, padding: '24px 56px 56px', borderBottom: `1px solid ${TC.line}` }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 48, alignItems: 'end' }}>
          <div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: TC.greenSoft, color: TC.greenInk, fontWeight: 700, fontSize: 12.5, padding: '7px 14px', borderRadius: 999, marginBottom: 18 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: TC.green }} /> {c.cat}{numberLabel && ` ／ ${numberLabel}`}
            </div>
            <h1 style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 44, fontWeight: 900, color: TC.ink, margin: 0, lineHeight: 1.35, letterSpacing: '-0.02em', fontFeatureSettings: "'palt'" }}>
              {c.work}
            </h1>
            <p style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 15.5, color: TC.ink70, lineHeight: 2.1, marginTop: 18, maxWidth: 540 }}>
              {c.summary}
            </p>
          </div>
          <ImgC src={c.after} ratio="4/3" radius={6} alt={`${c.work}（${c.cat}）の施工後写真`} />
        </div>
      </section>

      {/* 工事概要 */}
      <section style={{ background: '#fff', padding: '64px 56px', borderBottom: `1px solid ${TC.line}` }}>
        <SHC num="01" en="OVERVIEW" title="工事の概要" align="left" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 0 }}>
          {[
            ['所在地',  c.area],
            ['築年数',  c.year],
            ['工種',    c.work],
            ['工期',    c.term],
          ].map(([k, v], i) => (
            <div key={k} style={{
              display: 'grid', gridTemplateColumns: '180px 1fr', gap: 24,
              padding: '20px 24px',
              borderBottom: i < 3 ? `1px solid ${TC.line}` : 'none',
              borderRight: i % 2 === 0 ? `1px solid ${TC.line}` : 'none',
            }}>
              <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 11, color: TC.green, letterSpacing: 2, fontWeight: 700, paddingTop: 4 }}>{k}</div>
              <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 15, color: TC.ink, lineHeight: 1.7 }}>{v}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Before / After 大判 */}
      <section style={{ background: TC.paper, padding: '64px 56px', borderBottom: `1px solid ${TC.line}` }}>
        <SHC num="02" en="BEFORE / AFTER" title="施工事例（ビフォー・アフター）" lead="屋根は普段見えにくい場所だからこそ、工事の前後の写真を撮影し、お客様と一緒に状況を確認できるようにしています。" align="left" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
          <div>
            <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 12, color: TC.ink50, letterSpacing: 3, marginBottom: 10, fontWeight: 700 }}>BEFORE</div>
            <ImgC src={c.before} ratio="4/3" radius={6} alt={`${c.work}（${c.cat}）の施工前写真`} style={{ filter: 'saturate(0.65) brightness(0.95)' }} />
          </div>
          <div>
            <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 12, color: TC.green, letterSpacing: 3, marginBottom: 10, fontWeight: 700 }}>AFTER</div>
            <ImgC src={c.after} ratio="4/3" radius={6} alt={`${c.work}（${c.cat}）の施工後写真`} />
          </div>
        </div>
      </section>

      {/* 工事の流れ */}
      {flow.length > 0 && <section data-empty-contract="case-flow" data-case-id={c.id} style={{ background: '#fff', padding: '64px 56px', borderBottom: `1px solid ${TC.line}` }}>
        <SHC num="03" en="ON SITE" title="工事の流れ" align="left" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 32 }}>
          {flow.map((x, i) => {
            const hasCopy = hasTextC(x.t) || hasTextC(x.d);
            const hasImage = hasImageRefC(x.ph);
            const columns = hasCopy && hasImage ? '60px 1fr 2fr' : '60px 1fr';
            return (
              <div key={i} data-empty-row style={{ display: 'grid', gridTemplateColumns: columns, gap: 24, alignItems: 'center', paddingBottom: 28, borderBottom: i < flow.length - 1 ? `1px solid ${TC.line}` : 'none' }}>
                <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 32, fontWeight: 700, color: TC.green, lineHeight: 1 }}>{String(i + 1).padStart(2, '0')}</div>
                {hasCopy && <div>
                  {hasTextC(x.t) && <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 20, fontWeight: 700, color: TC.ink, marginBottom: hasTextC(x.d) ? 10 : 0 }}>{x.t}</div>}
                  {hasTextC(x.d) && <div style={{ fontSize: 13.5, color: TC.ink70, lineHeight: 1.95 }}>{x.d}</div>}
                </div>}
                {hasImage && <ImgC src={x.ph} ratio="16/9" radius={6} alt={`${c.work}の工程${i + 1}（${x.t}）写真`} />}
              </div>
            );
          })}
        </div>
      </section>}

      {/* 関連事例 */}
      <section style={{ background: '#fff', padding: '64px 56px', borderBottom: `1px solid ${TC.line}` }}>
        <SHC num={relatedSectionNumber} en="RELATED" title="関連する施工事例" anchorRight={
          <a href={hrefC('cases')} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 12, color: TC.ink, fontSize: 13.5, fontWeight: 700, borderBottom: `1.5px solid ${TC.ink}`, paddingBottom: 3, textDecoration: 'none' }}>
            施工事例をすべて見る <IcC.arrow width="14" height="14" />
          </a>
        } />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          {CASESC.slice(1, 4).map((cc) => (
            <a key={cc.id} href={caseHrefC(cc.id)} style={{ display: 'block', borderRadius: 6, overflow: 'hidden', background: '#fff', border: `1px solid ${TC.line}`, textDecoration: 'none' }}>
              <ImgC src={cc.photo || cc.after} ratio="4/3" alt={`${cc.work}（${cc.cat}）の施工写真`} />
              <div style={{ padding: 18 }}>
                {caseNumberC(cc.id) && (
                  <div style={{ fontSize: 11, color: TC.ink50, fontWeight: 700, letterSpacing: 1.5, marginBottom: 8 }}>{caseNumberC(cc.id)}</div>
                )}
                <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 16, fontWeight: 700, color: TC.ink, lineHeight: 1.5, marginBottom: 6 }}>{cc.work}</div>
                <div style={{ fontSize: 12, color: TC.ink70 }}>{cc.area}</div>
              </div>
            </a>
          ))}
        </div>
      </section>
    </PageC>
  );
}

window.PageCasesIndex = PageCasesIndex;
window.PageCaseDetail = PageCaseDetail;
