// ============================================================
// APPLICATIONS — hub + per-industry detail page
// Direction B aesthetic.
// ============================================================

// Per-application content. Glass is built out fully; others get
// the same structure with their own data.
const APPLICATION_CONTENT = {
  glass: {
    hero_image: 'assets/product-vials.jpg',
    intro: "From flat float lines to amber container batches, the glass industry has specified U.S. Silica grades for more than a century. Our Mid-Atlantic Oriskany seam gives us the iron-poor chemistry container engineers expect — and the lot stability they don't have to argue with.",
    grade_skus: ['MX-30/50', 'GS-49', 'TG-2030'],
    sub_apps: [
      { name: 'Container glass', desc: 'Flint, amber, green. Default spec is MX-30/50.' },
      { name: 'Float / flat glass', desc: 'Iron below 90 ppm for architectural lines.' },
      { name: 'Fiberglass', desc: 'Tighter D50 cuts available on request.' },
      { name: 'Solar PV cover glass', desc: 'Iron below 80 ppm; specialty re-cut.' },
      { name: 'Specialty optical', desc: 'Custom chemistry; ask about Ti & Al floors.' },
      { name: 'Tableware & lighting', desc: 'Re-melt grade; tight color consistency.' },
    ],
    spec_table: [
      ['SiO₂ minimum', '99.7%', '99.5–99.9%'],
      ['Iron content', '≤ 90 ppm', '60–110 ppm'],
      ['Titanium', '≤ 0.03%', '0.02–0.04%'],
      ['Mesh range', '30/50 standard', 'Custom re-cuts'],
    ],
    case_study: {
      title: 'How a top-3 container manufacturer cut tank-life variance by 38%',
      blurb: 'A west-coast container plant moved from a Mid-Continent grade to MX-30/50 with a 6-week parallel run. The result: 38% reduction in tank-life variance and 14% lower colorant usage on amber lines.',
      result: ['38%', 'tank-life variance reduction'],
    },
  },
  foundry: {
    hero_image: 'assets/lab-samples.jpg',
    intro: "Foundry sand is the original industrial silica application. Round, friable grains from the St. Peter sandstone behave the way casting engineers expect — predictable AFS GFN, controlled moisture, lot-stable refractoriness.",
    grade_skus: ['MX-30/50', 'QR-100', 'TG-2030'],
    sub_apps: [
      { name: 'Green sand · ferrous', desc: 'Round St. Peter grains, AFS GFN 50–65.' },
      { name: 'Resin-bonded shell', desc: 'High permeability for thin-wall castings.' },
      { name: 'No-bake systems', desc: 'Low fines, controlled clay content.' },
      { name: 'Investment casting', desc: 'Fine, narrow-cut for surface finish.' },
      { name: 'Core sand', desc: 'Air-set and cold-box systems.' },
      { name: 'Refractory aggregates', desc: 'High-purity for monolithic linings.' },
    ],
    spec_table: [
      ['AFS GFN', '50–65', 'Customizable cut'],
      ['Acid demand value', '≤ 5 ml', '< 5 ml typical'],
      ['Loss on ignition', '≤ 0.20%', '0.10–0.18%'],
      ['Clay content', '≤ 0.5%', '0.2–0.4%'],
    ],
    case_study: {
      title: 'A heavy-truck foundry stabilized GFN to ±1 grain across 18 months',
      blurb: 'Switching to U.S. Silica foundry sand from a regional source brought monthly AFS GFN variance down to ±1 grain, freeing the molding line from weekly recalibration.',
      result: ['±1', 'AFS GFN variance · 18 mo'],
    },
  },
  building: {
    hero_image: 'assets/app-countertop.jpg',
    intro: "Engineered stone, grout, mortar, roofing granules, and decorative aggregates. Our Q-Rok, GS-30, and specialty grades give building-products formulators predictable rheology and tight color control.",
    grade_skus: ['QR-100', 'GS-49'],
    sub_apps: [
      { name: 'Engineered stone', desc: 'Crystalline quartz aggregate, multiple mesh.' },
      { name: 'Tile grout & mortar', desc: 'Color-stable filler for cementitious systems.' },
      { name: 'Roofing granules', desc: 'Hard, angular, weather-resistant.' },
      { name: 'Decorative aggregates', desc: 'White and natural color blends.' },
      { name: 'Caulk & sealant filler', desc: 'Predictable oil absorption.' },
      { name: 'Asphalt aggregate', desc: 'Crush-resistant fine sand.' },
    ],
    spec_table: [
      ['SiO₂', '≥ 99.4%', '99.4–99.7%'],
      ['Hardness (Mohs)', '7.0', '7.0'],
      ['Color (L*)', '≥ 92', 'White grades only'],
      ['Crush (3000 psi)', '< 7%', 'Construction grade'],
    ],
    case_study: {
      title: 'Engineered-stone fabricator cuts filler variance by 41%',
      blurb: 'A Tier-1 countertop fabricator standardized on U.S. Silica Q-Rok 100, lowering batch-to-batch filler variance by 41% and reducing reject panels by 22% in the first quarter.',
      result: ['41%', 'filler variance reduction'],
    },
  },
  oilgas: {
    hero_image: 'assets/frac-sand.jpg',
    intro: "API-tested proppant from in-basin facilities in Texas. FracPro 100 is qualified to API RP-19C and ships from our Kosse and Voca mines with rail and bulk-truck dispatch across the Permian and Eagle Ford basins.",
    grade_skus: ['FS-100', 'QR-100'],
    sub_apps: [
      { name: 'Hydraulic fracturing', desc: 'API RP-19C qualified frac sand.' },
      { name: 'Gravel pack', desc: 'Narrow-cut, round grains for completions.' },
      { name: 'Sand control', desc: 'High-conductivity proppants.' },
      { name: 'In-basin logistics', desc: 'Direct dispatch from Permian / Eagle Ford.' },
    ],
    spec_table: [
      ['API RP-19C', 'Qualified', 'Per-lot tested'],
      ['Crush resistance @ 4k', '< 10%', 'Typical 6–8%'],
      ['Sphericity', '≥ 0.6', 'Typical 0.65–0.70'],
      ['Roundness', '≥ 0.6', 'Typical 0.65'],
    ],
    case_study: {
      title: 'In-basin Permian operator cut proppant logistics cost by 19%',
      blurb: 'Switching to U.S. Silica in-basin FracPro 100 from a North-American mine eliminated 1,800 miles of trucking per well, dropping all-in proppant logistics cost by 19% on the same play.',
      result: ['19%', 'logistics cost saved'],
    },
  },
  coatings: {
    hero_image: 'assets/ground-silica.jpg',
    intro: "Functional fillers and extenders for paints, coatings, sealants, and polymer composites. Predictable rheology, low oil-absorption, and a tight median particle size that holds across hundreds of lots.",
    grade_skus: ['GS-49', 'MU-5'],
    sub_apps: [
      { name: 'Architectural paint', desc: 'Matting and texture extender.' },
      { name: 'Powder coatings', desc: 'Anti-blocking and surface texture.' },
      { name: 'Epoxy & polyester', desc: 'High-loading filler for composites.' },
      { name: 'Silicone sealants', desc: 'Reinforcing, low-oil-absorption.' },
      { name: 'Specialty composites', desc: 'Sub-micron grades on request.' },
      { name: 'Adhesives', desc: 'Predictable thixotropy.' },
    ],
    spec_table: [
      ['D50 (median)', '5.1 µm', '5.0–5.3 µm'],
      ['Surface area (BET)', '4.2 m²/g', '4.0–4.5 m²/g'],
      ['Oil absorption', '24 g / 100g', '22–26'],
      ['Brightness (L*)', '93', '> 92'],
    ],
    case_study: {
      title: 'A pigment formulator hit ±2% color variance across 12 months',
      blurb: 'Standardizing on Min-U-Sil 5 brought architectural-paint color variance into a ±2% band across a full year of production, eliminating two seasonal re-calibrations.',
      result: ['±2%', 'color variance · 12 mo'],
    },
  },
  filtration: {
    hero_image: 'assets/testing-sand.jpg',
    intro: "Municipal and industrial water filtration. NSF/ANSI 61 certified silica filter sand and support gravel with consistent effective size and uniformity coefficient.",
    grade_skus: ['MX-30/50', 'QR-100'],
    sub_apps: [
      { name: 'Municipal drinking water', desc: 'NSF/ANSI 61 certified.' },
      { name: 'Wastewater treatment', desc: 'Tertiary filtration media.' },
      { name: 'Industrial process water', desc: 'Heavy-metal removal beds.' },
      { name: 'Swimming pool & spa', desc: 'NSF 50 listed.' },
    ],
    spec_table: [
      ['Effective size (ES)', '0.45–0.55 mm', 'NSF 61 spec'],
      ['Uniformity coeff.', '≤ 1.5', 'Typical 1.3'],
      ['SiO₂', '≥ 99.4%', '99.4–99.7%'],
      ['NSF/ANSI 61', 'Listed', 'Annual audit'],
    ],
    case_study: {
      title: 'A Midwest municipal plant replaced filter media on a 7-year cycle',
      blurb: 'Lifecycle data from 14 municipal water districts using U.S. Silica filter sand shows an average media-replacement cycle of 7.2 years vs. the industry benchmark of 5 years.',
      result: ['7.2 yrs', 'avg media lifecycle'],
    },
  },
};

function ApplicationsHub({ onNavigate }) {
  return (
    <div className="dir-b ab-page">
      <BrowserChrome url="ussilica.com/applications" />
      <NavB onNavigate={onNavigate}/>
      <PageHeader title="Applications" subtitle="Six industries. Hundreds of finished products. The same lot of silica shows up in your kitchen counter, the bottle on the shelf, the engine block under the hood."
        breadcrumbs={['Home', 'Applications']} onNavigate={onNavigate}/>

      <section style={{ padding: '64px 32px 96px', background: 'var(--bg)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
          {APPLICATIONS.map((a, i) => (
            <article key={a.id} onClick={() => onNavigate('application', { id: a.id })}
              style={{ background: 'var(--paper)', borderRadius: 12, overflow: 'hidden', cursor: 'pointer', border: '1px solid var(--line)', transition: 'all .15s' }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent)'}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--line)'}>
              <div style={{ position: 'relative', height: 240 }}>
                <Photo src={a.image} height="100%"/>
                <span style={{ position: 'absolute', top: 14, left: 14, padding: '4px 8px', background: 'rgba(10,10,10,0.65)', color: '#fff', borderRadius: 4, fontFamily: 'IBM Plex Mono', fontSize: 10 }}>
                  № {String(i + 1).padStart(2, '0')}
                </span>
              </div>
              <div style={{ padding: 24 }}>
                <h2 className="display" style={{ fontSize: 28, margin: 0, fontWeight: 500 }}>{a.name}</h2>
                <p style={{ fontSize: 14, color: 'var(--ink-soft)', margin: '8px 0 14px', lineHeight: 1.5 }}>{a.tagline}</p>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 14, borderTop: '1px solid var(--line)' }}>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{a.count} GRADES</div>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--accent)', fontSize: 13 }}>Explore <Icon.arrow size={13}/></span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>

      <section style={{ padding: '80px 32px', background: 'var(--paper)', borderTop: '1px solid var(--line)' }}>
        <h2 className="display" style={{ fontSize: 40, margin: 0, fontWeight: 500 }}>Don't see your application?</h2>
        <p style={{ fontSize: 16, color: 'var(--ink-soft)', marginTop: 12, maxWidth: 640, lineHeight: 1.55 }}>
          We've shipped industrial silica into specialty applications we can't name publicly — semiconductor cleanrooms,
          aerospace composites, medical-device manufacturing. Tell us what you're making.
        </p>
        <div style={{ marginTop: 28, display: 'flex', gap: 12 }}>
          <MagButton variant="primary" size="lg" dir="b" onClick={() => onNavigate('rfq')}>Talk to a specialist <Icon.arrow size={14}/></MagButton>
          <MagButton variant="ghost" size="lg" dir="b" onClick={() => onNavigate('products')}>Browse all grades</MagButton>
        </div>
      </section>

      <FooterB onNavigate={onNavigate}/>
    </div>
  );
}

function ApplicationDetail({ onNavigate, params }) {
  const id = params?.id || 'glass';
  const app = APPLICATIONS.find(a => a.id === id) || APPLICATIONS[0];
  const content = APPLICATION_CONTENT[id] || APPLICATION_CONTENT.glass;
  const products = PRODUCTS.filter(p => content.grade_skus.includes(p.sku));

  return (
    <div className="dir-b ab-page">
      <BrowserChrome url={`ussilica.com/applications/${id}`} />
      <NavB onNavigate={onNavigate}/>
      <PageHeader
        title={app.name + ' applications'}
        subtitle={app.tagline}
        eyebrow={`APPLICATION · № ${String(APPLICATIONS.findIndex(a => a.id === id) + 1).padStart(2, '0')}`}
        breadcrumbs={['Home', 'Applications', app.name]}
        onNavigate={onNavigate}
        dark cover={content.hero_image}
        height={460}
      />

      {/* Intro */}
      <section style={{ padding: '64px 32px', background: 'var(--paper)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 56, alignItems: 'start' }}>
          <p style={{ fontSize: 22, lineHeight: 1.5, margin: 0, color: 'var(--ink)' }}>
            {content.intro}
          </p>
          <div style={{ background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 12, padding: 22 }}>
            <div className="label-mono" style={{ marginBottom: 14 }}>AT A GLANCE</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                <span style={{ color: 'var(--ink-soft)' }}>Active grades</span>
                <span className="mono" style={{ fontWeight: 500 }}>{app.count}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                <span style={{ color: 'var(--ink-soft)' }}>Producing facilities</span>
                <span className="mono" style={{ fontWeight: 500 }}>14 of 27</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                <span style={{ color: 'var(--ink-soft)' }}>Avg lead time (bulk)</span>
                <span className="mono" style={{ fontWeight: 500 }}>3–5 days</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                <span style={{ color: 'var(--ink-soft)' }}>API / NSF / ISO</span>
                <span className="mono" style={{ fontWeight: 500 }}>Where applicable</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Sub-applications */}
      <section style={{ padding: '0 32px 64px', background: 'var(--paper)' }}>
        <div className="label-mono" style={{ marginBottom: 18 }}>SUB-APPLICATIONS</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
          {content.sub_apps.map((s, i) => (
            <div key={i} style={{ padding: 22, background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 10 }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>0{i + 1}</div>
              <h3 style={{ fontSize: 17, margin: '8px 0 6px', fontWeight: 500 }}>{s.name}</h3>
              <p style={{ fontSize: 13, color: 'var(--ink-soft)', margin: 0, lineHeight: 1.5 }}>{s.desc}</p>
            </div>
          ))}
        </div>
      </section>

      {/* Spec snapshot */}
      <section style={{ padding: '80px 32px', background: 'var(--bg)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 56 }}>
          <div>
            <div className="label-mono">[02] · SPEC SNAPSHOT</div>
            <h2 className="display" style={{ fontSize: 44, margin: '12px 0 0', fontWeight: 500 }}>
              The chemistry behind {app.name.toLowerCase()}.
            </h2>
            <p style={{ marginTop: 16, fontSize: 15, color: 'var(--ink-soft)', lineHeight: 1.55, maxWidth: 400 }}>
              These are the parameters {app.name.toLowerCase()} engineers actually quote against. Full per-grade specs are on the individual product pages.
            </p>
          </div>
          <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
            <div className="mono" style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 1.6fr', padding: '14px 22px', borderBottom: '1px solid var(--line)', fontSize: 11, color: 'var(--ink-soft)', textTransform: 'uppercase' }}>
              <span>Parameter</span><span>Specification</span><span>Typical</span>
            </div>
            {content.spec_table.map((r, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 1.6fr', padding: '14px 22px', borderBottom: i < content.spec_table.length - 1 ? '1px solid var(--line)' : 'none', alignItems: 'center', fontSize: 14 }}>
                <span style={{ fontWeight: 500 }}>{r[0]}</span>
                <span className="mono" style={{ color: 'var(--accent)' }}>{r[1]}</span>
                <span className="mono" style={{ color: 'var(--ink-soft)' }}>{r[2]}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Grades for this application */}
      <section style={{ padding: '80px 32px', background: 'var(--paper)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 24 }}>
          <div>
            <div className="label-mono">[03] · GRADES</div>
            <h2 className="display" style={{ fontSize: 44, margin: '12px 0 0', fontWeight: 500 }}>Recommended grades for {app.name.toLowerCase()}.</h2>
          </div>
          <a onClick={() => onNavigate('products')} style={{ fontSize: 14, color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
            View all {app.count} grades <Icon.arrow size={13}/>
          </a>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${products.length}, 1fr)`, gap: 16 }}>
          {products.map(p => (
            <article key={p.sku} onClick={() => onNavigate('product', { sku: p.sku })}
              style={{ background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden', cursor: 'pointer' }}>
              <Photo src={p.image} height={200}/>
              <div style={{ padding: 18 }}>
                <div className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{p.sku}</div>
                <h3 style={{ fontSize: 18, margin: '6px 0 4px', fontWeight: 500 }}>{p.name}</h3>
                <p style={{ fontSize: 13, color: 'var(--ink-soft)', margin: '0 0 12px', lineHeight: 1.45 }}>{p.summary}</p>
                <div style={{ display: 'flex', gap: 12, fontFamily: 'IBM Plex Mono', fontSize: 11, color: 'var(--ink-soft)', paddingTop: 10, borderTop: '1px solid var(--line)' }}>
                  <span>{p.silica_pct}%</span><span>{p.iron_ppm} ppm</span><span>{p.mesh}</span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>

      {/* Case study */}
      <section style={{ padding: '96px 32px', background: 'var(--bg-deep)', color: 'var(--paper)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 64, alignItems: 'center' }}>
          <div>
            <div className="label-mono" style={{ color: 'oklch(0.78 0.13 70)' }}>[04] · CASE STUDY</div>
            <h2 className="display" style={{ fontSize: 48, margin: '14px 0', color: 'var(--paper)', fontWeight: 500, lineHeight: 1.1 }}>
              {content.case_study.title}
            </h2>
            <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.75)', lineHeight: 1.6, maxWidth: 540 }}>
              {content.case_study.blurb}
            </p>
            <button onClick={() => onNavigate('newsroom')} style={{ marginTop: 28, padding: '12px 18px', background: 'transparent', border: '1px solid rgba(255,255,255,0.3)', color: 'var(--paper)', borderRadius: 6, fontSize: 14, fontFamily: 'IBM Plex Sans', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              Read the full study <Icon.arrow size={13}/>
            </button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }}>
            <div style={{ padding: 36, borderRight: '1px solid rgba(255,255,255,0.15)' }}>
              <div className="display" style={{ fontSize: 96, color: 'var(--paper)', fontWeight: 500, lineHeight: 1 }}>{content.case_study.result[0]}</div>
              <div className="label-mono" style={{ color: 'rgba(255,255,255,0.6)', marginTop: 8 }}>{content.case_study.result[1]}</div>
            </div>
            <div style={{ padding: 36 }}>
              <div style={{ aspectRatio: '4 / 5', borderRadius: 8, overflow: 'hidden', background: '#000' }}>
                <Photo src={content.hero_image} height="100%"/>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Related applications */}
      <section style={{ padding: '64px 32px', background: 'var(--paper)' }}>
        <div className="label-mono" style={{ marginBottom: 18 }}>RELATED APPLICATIONS</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14 }}>
          {APPLICATIONS.filter(a => a.id !== id).map(a => (
            <a key={a.id} onClick={() => onNavigate('application', { id: a.id })}
              style={{ padding: 18, background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 8, cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 8, transition: 'border-color .15s' }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent)'}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--line)'}>
              <div style={{ fontSize: 15, fontWeight: 500 }}>{a.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{a.count} GRADES</div>
            </a>
          ))}
        </div>
      </section>

      <CtaB onNavigate={onNavigate}/>
      <FooterB onNavigate={onNavigate}/>
    </div>
  );
}

Object.assign(window, { ApplicationsHub, ApplicationDetail, APPLICATION_CONTENT });
