// Forge — Dossier (single-folio page).
// One engagement per page, selected by URL hash:
//   dossier.html#forge-boreal  → renders the boreal folio
//   dossier.html               → falls back to the first folio
//
// Same workshop visual language — anthracite, iron, ember, Cardo +
// JetBrains Mono — pitched as a bound technical file rather than a
// marketing page.

// ---------- shared atoms ----------
const dMonoLabel = {
  fontFamily: 'var(--font-mono)', fontSize: 11,
  letterSpacing: '0.22em', textTransform: 'uppercase',
};
const dIron = { color: 'var(--forge-iron-soft)' };
const dIronBright = { color: 'var(--forge-iron-bright)' };
const dEmber = { color: 'var(--forge-ember)' };

const pad2 = (n) => String(n).padStart(2, '0');

// the compass, smaller stamp
const DossierMark = ({ size = 32 }) => (
  <svg width={size} height={size} viewBox="0 0 200 200" aria-hidden="true" style={{display: 'block'}}>
    <path d="M 10 10 L 90 90 L 95 100 L 90 110 L 10 10 Z" fill="#d8dde3" opacity="0.92"/>
    <path d="M 190 10 L 110 90 L 105 100 L 110 110 L 190 10 Z" fill="#d8dde3" opacity="0.92"/>
    <path d="M 10 190 L 90 110 L 100 105 L 110 110 L 10 190 Z" fill="#d8dde3" opacity="0.45"/>
    <path d="M 190 190 L 110 110 L 100 105 L 90 110 L 190 190 Z" fill="#d8dde3" opacity="0.45"/>
    <circle cx="100" cy="100" r="8" fill="#e8623a"/>
  </svg>
);

// ---------- nav ----------
const DossierNav = ({ c }) => (
  <div className="ds-nav" style={{
    background: 'rgba(20, 22, 26, 0.92)',
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
    borderBottom: '1px solid var(--forge-rule-mid)',
  }}>
    <DossierMark size={24}/>
    <a href="index.html" style={{...dMonoLabel, ...dIronBright, textDecoration: 'none'}}>XLBS / FORGE</a>
    <span style={{...dMonoLabel, color: 'var(--forge-iron)'}}>·</span>
    <span style={{...dMonoLabel, ...dEmber}}>DOSSIER · {c.code}</span>

    <div className="ds-nav-links">
      <a href="index.html#work" style={{...dMonoLabel, ...dIron, textDecoration: 'none'}}>← Selected work</a>
      <a href="index.html#brief" style={{...dMonoLabel, ...dEmber, textDecoration: 'none'}}>Open a brief →</a>
    </div>
  </div>
);

// ---------- meter strip ----------
const DossierMeter = ({ c }) => (
  <div className="ds-meter">
    <div style={{display: 'flex', alignItems: 'flex-end', gap: 0, marginRight: 24}}>
      {Array.from({length: 28}).map((_, i) => (
        <div key={i} style={{
          width: 1,
          height: i % 5 === 0 ? 14 : 7,
          background: i % 5 === 0 ? 'var(--forge-iron-soft)' : 'var(--forge-iron)',
          marginRight: 8,
        }}/>
      ))}
    </div>
    <span>FOLIO · {c.code}</span>
    <span style={{margin: '0 14px', opacity: 0.4}}>·</span>
    <span>{c.year}</span>
    <span style={{margin: '0 14px', opacity: 0.4}}>·</span>
    <span>VIA {c.lab.toUpperCase()}</span>
    <span style={{margin: '0 14px', opacity: 0.4}}>·</span>
    <span>{c.offers.join(' · ')}</span>
    <span style={{marginLeft: 'auto'}}>EDITION 2026.04</span>
  </div>
);

// =====================================================================
// FOLIO — the case sheet
// =====================================================================
const Folio = ({ c }) => (
  <section id={c.slug} style={{
    background: 'var(--forge-anthracite)',
    borderBottom: '1px solid var(--forge-rule-mid)',
  }}>
    <div className="ds-folio-pad">
      <div className="ds-col">

        {/* title block */}
        <div className="ds-folio-title">
          <div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 18, letterSpacing: '0.2em',
              color: 'var(--forge-ember)', border: '1px solid var(--forge-ember)',
              padding: '12px 16px', display: 'inline-block',
            }}>{c.code}</div>
            <div style={{
              marginTop: 20, ...dMonoLabel, ...dIron, lineHeight: 1.8,
            }}>
              {c.year}<br/>
              {c.offers.join(' · ')}<br/>
              {c.lab.toUpperCase()}
            </div>
          </div>
          <div>
            <div style={{...dMonoLabel, ...dEmber, marginBottom: 16}}>● {c.sector.toUpperCase()}</div>
            <h1 className="forge-h2" style={{
              margin: 0, color: 'var(--forge-iron-bright)',
              fontSize: 'clamp(40px, 5.5vw, 68px)',
              lineHeight: 1.04, letterSpacing: '-0.015em',
            }}>{c.title}</h1>
            <div style={{
              marginTop: 22, fontFamily: 'var(--font-serif)', fontStyle: 'italic',
              fontSize: 22, lineHeight: 1.4, color: 'var(--forge-iron-soft)',
            }}>
              {c.client_type}
            </div>
          </div>
        </div>

        {/* hero schematic */}
        <div style={{
          marginTop: 56,
          border: '1px solid var(--forge-rule-mid)',
          background: 'var(--forge-anthracite)',
        }}>
          <c.Hero/>
        </div>

        {/* problem + approach */}
        <div className="ds-folio-cols" style={{marginTop: 64}}>
          <Block label="01 · PROBLEM" body={c.problem}/>
          <Block label="02 · APPROACH" body={c.approach}/>
        </div>

        {/* spec schedule */}
        <ScheduleTable c={c}/>

        {/* stack */}
        <div style={{marginTop: 64}}>
          <div style={{...dMonoLabel, ...dIron, marginBottom: 16}}>03 · STACK</div>
          <div style={{
            display: 'flex', flexWrap: 'wrap', gap: 8,
            borderTop: '1px solid var(--forge-rule-dark)',
            paddingTop: 16,
          }}>
            {c.stack.map((s) => (
              <span key={s} style={{
                fontFamily: 'var(--font-mono)', fontSize: 12.5, letterSpacing: '0.04em',
                color: 'var(--forge-iron-bright)',
                border: '1px solid var(--forge-rule-mid)',
                padding: '7px 11px',
              }}>{s}</span>
            ))}
          </div>
        </div>

        {/* deliverables */}
        <div style={{marginTop: 64}}>
          <div style={{...dMonoLabel, ...dIron, marginBottom: 16}}>04 · DELIVERABLES</div>
          <ol className={c.deliverables.length > 5 ? 'ds-deliverables-2col' : ''} style={{
            listStyle: 'none', margin: 0, padding: 0,
            borderTop: '1px solid var(--forge-rule-dark)',
          }}>
            {c.deliverables.map((d, i) => (
              <li key={i} style={{
                display: 'grid', gridTemplateColumns: '36px 1fr',
                gap: 14, padding: '12px 0',
                borderBottom: '1px solid var(--forge-rule-dark)',
                breakInside: 'avoid',
              }}>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em',
                  color: 'var(--forge-ember)',
                }}>D{pad2(i + 1)}</span>
                <span style={{
                  fontFamily: 'var(--font-serif)', fontSize: 16, lineHeight: 1.45,
                  color: 'var(--forge-iron-bright)',
                }}>{d}</span>
              </li>
            ))}
          </ol>
        </div>

        {/* published — public access */}
        {c.published && c.published.length > 0 && (
          <PublishedSection items={c.published}/>
        )}

        {/* outcome — ember plate */}
        <div className="ds-folio-outcome" style={{
          marginTop: 64,
          background: 'var(--forge-ember)',
          color: 'var(--forge-anthracite)',
        }}>
          <div style={{
            ...dMonoLabel,
            color: 'var(--forge-anthracite)',
            opacity: 0.75,
          }}>05 · OUTCOME</div>
          <div style={{
            fontFamily: 'var(--font-serif)', fontSize: 24, lineHeight: 1.45,
            color: 'var(--forge-anthracite)',
          }}>{c.outcome}</div>
        </div>

      </div>
    </div>

    {/* sheet footer */}
    <div className="ds-folio-footer" style={{...dMonoLabel, ...dIron}}>
      <span>END OF FOLIO · {c.code}</span>
      <a href="index.html#work" style={{...dIron, textDecoration: 'none'}}>↑ SELECTED WORK</a>
      <span>SIGNED · XLBS · FORGE</span>
    </div>
  </section>
);

// ---------- folio sub-blocks ----------
const Block = ({ label, body }) => (
  <div style={{borderTop: '1px solid var(--forge-rule-dark)', paddingTop: 16}}>
    <div style={{...dMonoLabel, ...dIron, marginBottom: 12}}>{label}</div>
    <p style={{
      margin: 0, fontFamily: 'var(--font-serif)', fontSize: 17.5, lineHeight: 1.6,
      color: 'var(--forge-iron-bright)',
    }}>{body}</p>
  </div>
);

const ScheduleTable = ({ c }) => {
  const rows = [
    ['SECTOR', c.sector],
    ['CLIENT', c.client_type],
    ['LAB', c.lab],
    ['SCOPE', c.offers.join(' · ')],
    ['DURATION', c.duration],
    ['DATA VOLUME', c.data_volume],
    ['KEY METRIC', `${c.key_metric.value} (${c.key_metric.label})`],
  ];
  return (
    <div style={{marginTop: 64}}>
      <div style={{...dMonoLabel, ...dIron, marginBottom: 16}}>SCHEDULE</div>
      <div style={{borderTop: '1px solid var(--forge-rule-mid)'}}>
        {rows.map(([k, v]) => {
          const isMetric = k === 'KEY METRIC';
          return (
            <div key={k} className="ds-schedule-row">
              <div style={{...dMonoLabel, ...dIron}}>{k}</div>
              <div style={{
                fontFamily: isMetric ? 'var(--font-mono)' : 'var(--font-serif)',
                fontSize: 16,
                color: isMetric ? 'var(--forge-ember)' : 'var(--forge-iron-bright)',
                letterSpacing: isMetric ? '0.04em' : 'normal',
                lineHeight: 1.5,
              }}>{v}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const PublishedSection = ({ items }) => (
  <div style={{marginTop: 64}}>
    <div style={{...dMonoLabel, ...dIron, marginBottom: 16}}>06 · PUBLISHED · PUBLIC ACCESS</div>
    <ol style={{listStyle: 'none', margin: 0, padding: 0, borderTop: '1px solid var(--forge-rule-dark)'}}>
      {items.map((item, i) => (
        <li key={i} style={{
          display: 'grid', gridTemplateColumns: '36px 1fr',
          gap: 14, padding: '16px 0',
          borderBottom: '1px solid var(--forge-rule-dark)',
        }}>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em',
            color: 'var(--forge-ember)', paddingTop: 2,
          }}>P{pad2(i + 1)}</span>
          <div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em',
              color: 'var(--forge-ember)', marginBottom: 6,
            }}>{item.type}</div>
            <div style={{
              fontFamily: 'var(--font-serif)', fontSize: 16, lineHeight: 1.45,
              color: 'var(--forge-iron-bright)', marginBottom: item.url || item.ref ? 8 : 0,
            }}>{item.title}</div>
            {item.url && (
              <a href={item.url} target="_blank" rel="noopener noreferrer" style={{
                display: 'inline-block',
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em',
                color: 'var(--forge-iron-soft)', textDecoration: 'none',
                borderBottom: '1px solid var(--forge-rule-mid)',
                paddingBottom: 1,
              }}>{item.url} →</a>
            )}
            {!item.url && item.ref && (
              <span style={{
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em',
                color: 'var(--forge-iron)',
              }}>{item.ref}</span>
            )}
          </div>
        </li>
      ))}
    </ol>
  </div>
);

// =====================================================================
// COLOPHON — closing plate
// =====================================================================
const Colophon = () => (
  <section style={{
    background: 'var(--forge-anthracite-2)',
    padding: 'clamp(56px, 8vw, 88px) clamp(20px, 4vw, 48px)',
    borderBottom: '1px solid var(--forge-rule-mid)',
  }}>
    <div className="ds-col">
      <div style={{display: 'flex', alignItems: 'baseline', gap: 16, marginBottom: 32}}>
        <span style={{...dMonoLabel, ...dEmber}}>● NEXT STEP</span>
        <span style={{flex: 1, height: 1, background: 'var(--forge-rule-mid)'}}/>
      </div>

      <div className="ds-colophon-grid">
        <div>
          <h2 className="forge-h2" style={{
            margin: 0, color: 'var(--forge-iron-bright)',
            fontSize: 'clamp(32px, 4.4vw, 52px)', lineHeight: 1.04, letterSpacing: '-0.01em',
          }}>
            What you read,<br/>
            <span style={{color: 'var(--forge-iron-soft)', fontStyle: 'italic'}}>I can do again.</span>
          </h2>
          <p style={{
            marginTop: 24, maxWidth: 540,
            fontFamily: 'var(--font-serif)', fontSize: 18, lineHeight: 1.55,
            color: 'var(--forge-iron-soft)',
          }}>
            The shape repeats: architecture into build, diagnosis into migration,
            build into stewardship. If this one looks like yours, open a brief.
          </p>

          <div style={{
            marginTop: 36, display: 'flex', alignItems: 'center', gap: 16,
            paddingTop: 24, borderTop: '1px solid var(--forge-rule-mid)',
          }}>
            <a href="index.html#brief" className="forge-btn"
               style={{background: 'var(--forge-ember)', color: 'var(--forge-anthracite)', textDecoration: 'none'}}>Open a brief</a>
            <a href="index.html" className="forge-btn forge-btn--ghost"
               style={{color: 'var(--forge-iron-bright)', borderColor: 'var(--forge-rule-mid)', textDecoration: 'none'}}>← Back to the workshop</a>
          </div>
        </div>

        <div className="ds-colophon-aside">
          {[
            ['SIGNATURE', 'XLBS · FORGE'],
            ['CONTACT', 'hello@xlbs.xyz'],
            ['REPLY', 'Two business days'],
          ].map(([k, v]) => (
            <div key={k} className="ds-colophon-row">
              <div style={{...dMonoLabel, ...dIron}}>{k}</div>
              <div style={{
                fontFamily: 'var(--font-serif)', fontSize: 16, lineHeight: 1.45,
                color: 'var(--forge-iron-bright)',
              }}>{v}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  </section>
);

// =====================================================================
// FOOTER
// =====================================================================
const DossierFooter = ({ c }) => (
  <footer style={{
    background: 'var(--forge-anthracite)',
    padding: 'clamp(32px, 5vw, 48px) clamp(20px, 4vw, 48px) clamp(24px, 4vw, 36px)',
  }}>
    <div className="ds-col">
      <div style={{display: 'flex', alignItems: 'center', gap: 18, marginBottom: 32, flexWrap: 'wrap'}}>
        <DossierMark size={36}/>
        <div>
          <div style={{...dMonoLabel, ...dIronBright}}>XLBS / FORGE</div>
          <div style={{...dMonoLabel, ...dIron, marginTop: 4}}>DOSSIER · {c.code} · EDITION 2026.05</div>
        </div>
        <div className="ds-footer-links">
          <a href="index.html" style={{...dMonoLabel, ...dIron, textDecoration: 'none'}}>Workshop</a>
          <a href="index.html#work" style={{...dMonoLabel, ...dIron, textDecoration: 'none'}}>Selected work</a>
          <a href="mailto:hello@xlbs.xyz" style={{...dMonoLabel, ...dIron, textDecoration: 'none'}}>hello@xlbs.xyz</a>
        </div>
      </div>
      <div className="ds-footer-bottom" style={{...dMonoLabel, color: 'var(--forge-iron)'}}>
        <span>{c.code} · REV 2026.05</span>
        <span>{window.FORGE.location}</span>
        <span>FORGED FOR PRODUCTION</span>
      </div>
    </div>
  </footer>
);

// =====================================================================
// NOT FOUND
// =====================================================================
const NotFound = ({ requested }) => (
  <div style={{
    minHeight: '100vh',
    display: 'flex', flexDirection: 'column',
    alignItems: 'center', justifyContent: 'center',
    padding: '48px', textAlign: 'center', gap: 24,
  }}>
    <div style={{...dMonoLabel, ...dEmber}}>● NO FOLIO ON FILE</div>
    <h1 className="forge-display" style={{
      margin: 0, color: 'var(--forge-iron-bright)',
      fontSize: 'clamp(56px, 10vw, 120px)',
      lineHeight: 0.9, letterSpacing: '-0.04em',
    }}>404<span style={{color: 'var(--forge-ember)'}}>.</span></h1>
    <p style={{
      margin: 0, fontFamily: 'var(--font-serif)', fontStyle: 'italic',
      fontSize: 22, color: 'var(--forge-iron-soft)', maxWidth: 480,
    }}>
      No dossier is filed under <span style={{
        fontFamily: 'var(--font-mono)', fontStyle: 'normal',
        color: 'var(--forge-iron-bright)',
      }}>#{requested}</span>.
    </p>
    <a href="index.html#work" className="forge-btn forge-btn--ghost"
       style={{color: 'var(--forge-iron-bright)', borderColor: 'var(--forge-rule-mid)', textDecoration: 'none'}}>
      ← Back to selected work
    </a>
  </div>
);

// =====================================================================
// COMPOSE
// =====================================================================
const readSlug = () => {
  if (typeof location === 'undefined') return '';
  return location.hash.replace(/^#/, '').trim();
};

const ForgeDossier = () => {
  const [cases, setCases] = React.useState([]);
  const [loaded, setLoaded] = React.useState(false);
  const [slug, setSlug] = React.useState(readSlug());

  React.useEffect(() => {
    (window.DOSSIER_CASES_PROMISE || Promise.resolve([]))
      .then((data) => { setCases(data); setLoaded(true); })
      .catch(() => setLoaded(true));
  }, []);

  React.useEffect(() => {
    const onHash = () => {
      setSlug(readSlug());
      window.scrollTo({top: 0, behavior: 'instant'});
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // empty hash → first folio; explicit-but-unknown hash → null
  const c = slug ? cases.find((x) => x.slug === slug) : cases[0];

  // keep the title in sync so each folio feels like its own page
  React.useEffect(() => {
    if (typeof document === 'undefined') return;
    document.title = c
      ? `${c.code} ${c.title} | Forge`
      : loaded ? 'Dossier | Forge' : 'Forge';
  }, [c, loaded]);

  if (!loaded) return null;
  if (slug && !c) return <NotFound requested={slug}/>;
  if (!c) return null;

  return (
    <div style={{
      position: 'relative', minHeight: '100%',
      background: 'var(--forge-anthracite)',
      color: 'var(--forge-iron-bright)',
      fontFamily: 'var(--font-serif)',
    }}>
      <DossierNav c={c}/>
      <DossierMeter c={c}/>
      <Folio c={c}/>
      <Colophon/>
      <DossierFooter c={c}/>
    </div>
  );
};

Object.assign(window, { ForgeDossier });
