// components.jsx — shared UI atoms & shell
const { useState, useEffect, useRef } = React;

// ---------- Logo mark ----------
function Mark({ size = 32 }) {
  return (
    <span className="mark" style={{ width: size, height: size }} aria-hidden="true"></span>
  );
}

// ---------- Top Navigation ----------
function Nav({ page, setPage, subBrand, setSubBrand }) {
  const links = [
    { id: 'home', label: 'Home' },
    { id: 'about', label: 'About' },
    { id: 'minerals', label: 'Minerals' },
    { id: 'lands', label: 'Lands' },
    { id: 'visit', label: 'Visit' },
    { id: 'projects', label: 'Projects' },
    { id: 'insights', label: 'Insights' },
    { id: 'careers', label: 'Careers' },
  ];
  return (
    <nav className="nav">
      <div className="nav-brand" onClick={() => setPage('home')}>
        <Mark />
        <span>Mamlakuwth</span>
      </div>
      <div className="nav-links">
        {links.map(l => (
          <a key={l.id}
             className={page === l.id ? 'active' : ''}
             onClick={(e) => { e.preventDefault(); setPage(l.id); }}
             href={`#${l.id}`}>
            {l.label}
          </a>
        ))}
      </div>
      <button className="nav-cta" onClick={() => setPage('contact')}>
        Get in touch
      </button>
    </nav>
  );
}

// ---------- Footer ----------
function Footer({ setPage }) {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
            <Mark size={28} />
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, letterSpacing: '0.02em' }}>
              Mamlakuwth
            </span>
          </div>
          <p className="footer-tag">Stewards of land &mdash; above and below.</p>
          <p style={{ fontSize: 14, color: 'rgba(232,226,208,0.7)', maxWidth: '36ch' }}>
            Mineral processing, supply-chain insight and heritage-led agriculture across Sub-Saharan Africa.
          </p>
        </div>
        <div>
          <h4>Minerals</h4>
          <ul>
            <li><a onClick={() => setPage('minerals')} href="#minerals">Feasibility studies</a></li>
            <li><a onClick={() => setPage('minerals')} href="#minerals">Due diligence</a></li>
            <li><a onClick={() => setPage('minerals')} href="#minerals">Processing optimisation</a></li>
            <li><a onClick={() => setPage('minerals')} href="#minerals">Tailings re-mining</a></li>
            <li><a onClick={() => setPage('projects')} href="#projects">Case studies</a></li>
          </ul>
        </div>
        <div>
          <h4>Lands</h4>
          <ul>
            <li><a onClick={() => setPage('lands')} href="#lands">Heritage crops</a></li>
            <li><a onClick={() => setPage('lands')} href="#lands">Regenerative practices</a></li>
            <li><a onClick={() => setPage('visit')} href="#visit">Farm stays</a></li>
            <li><a onClick={() => setPage('visit')} href="#visit">Harvest experiences</a></li>
            <li><a onClick={() => setPage('visit')} href="#visit">Guided tours</a></li>
          </ul>
        </div>
        <div>
          <h4>Company</h4>
          <ul>
            <li><a onClick={() => setPage('about')} href="#about">About</a></li>
            <li><a onClick={() => setPage('insights')} href="#insights">Insights</a></li>
            <li><a onClick={() => setPage('careers')} href="#careers">Careers</a></li>
            <li><a onClick={() => setPage('contact')} href="#contact">Contact</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-meta">
        <span>&copy; 2026 Mamlakuwth Consultancy.  Harare, Zimbabwe.</span>
        <span>Formerly Global Mining &amp; Processing Consultancy &middot; est. 2010</span>
      </div>
    </footer>
  );
}

// ---------- Image w/ placeholder fallback ----------
// Renders the striped placeholder, then overlays a real image on top
// once it has loaded. If the image errors, the placeholder remains.
function Ph({ label, height = 320, src, style = {}, position = 'center' }) {
  const [loaded, setLoaded] = React.useState(false);
  const [errored, setErrored] = React.useState(false);
  return (
    <div className="ph" style={{ height, ...style }}>
      <span className="ph-label" style={{ opacity: loaded && !errored ? 0 : 1, transition: 'opacity 0.4s ease' }}>{label}</span>
      {src && !errored && (
        <img
          src={src}
          alt={label}
          loading="lazy"
          onLoad={() => setLoaded(true)}
          onError={() => setErrored(true)}
          style={{
            position: 'absolute',
            inset: 0,
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            objectPosition: position,
            opacity: loaded ? 1 : 0,
            transition: 'opacity 0.6s ease',
          }}
        />
      )}
    </div>
  );
}

// Curated Unsplash photo URLs — themed by topic
const IMG = {
  // Minerals
  oreRocks:      'https://images.unsplash.com/photo-1518709268805-4e9042af9f23?w=1400&q=80&auto=format&fit=crop',
  mining:        'https://images.unsplash.com/photo-1473773508845-188df298d2d1?w=1400&q=80&auto=format&fit=crop',
  drillCore:     'https://images.unsplash.com/photo-1605557202138-c5e8e6ddb3a8?w=1400&q=80&auto=format&fit=crop',
  tailings:      'https://images.unsplash.com/photo-1582486225644-4d9c685fc8c4?w=1400&q=80&auto=format&fit=crop',
  oreSample:     'https://images.unsplash.com/photo-1518430435481-f1c1be6e7c1e?w=1400&q=80&auto=format&fit=crop',
  // Farm landscape — Zimbabwe / savanna
  farmField:     'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=1600&q=80&auto=format&fit=crop',
  savanna:       'https://images.unsplash.com/photo-1547471080-7cc2caa01a7e?w=1600&q=80&auto=format&fit=crop',
  miomboLand:    'https://images.unsplash.com/photo-1604665078253-b29ed29bd33c?w=1600&q=80&auto=format&fit=crop',
  aerialFarm:    'https://images.unsplash.com/photo-1625246333195-78d9c38ad449?w=1600&q=80&auto=format&fit=crop',
  // Horticulture
  tomatoes:      'https://images.unsplash.com/photo-1592924357228-91a4daadcfea?w=1400&q=80&auto=format&fit=crop',
  greenhouse:    'https://images.unsplash.com/photo-1530836369250-ef72a3f5cda8?w=1400&q=80&auto=format&fit=crop',
  carrots:       'https://images.unsplash.com/photo-1582515073490-39981397c445?w=1400&q=80&auto=format&fit=crop',
  peppers:       'https://images.unsplash.com/photo-1546470427-227df1e1e3e9?w=1400&q=80&auto=format&fit=crop',
  potatoes:      'https://images.unsplash.com/photo-1518977676601-b53f82aba655?w=1400&q=80&auto=format&fit=crop',
  vegetables:    'https://images.unsplash.com/photo-1447175008436-054170c2e979?w=1400&q=80&auto=format&fit=crop',
  herbs:         'https://images.unsplash.com/photo-1466637574441-749b8f19452f?w=1400&q=80&auto=format&fit=crop',
  // Livestock
  goats:         'https://images.unsplash.com/photo-1533347638999-ec3c2d80c4fd?w=1400&q=80&auto=format&fit=crop',
  boerGoat:      'https://images.unsplash.com/photo-1605479526938-95c5f1a85d97?w=1400&q=80&auto=format&fit=crop',
  poultry:       'https://images.unsplash.com/photo-1612170153139-6f881ff067e0?w=1400&q=80&auto=format&fit=crop',
  chickens:      'https://images.unsplash.com/photo-1556800619-d0fb946f1f74?w=1400&q=80&auto=format&fit=crop',
  // Chalets / hospitality
  chalet:        'https://images.unsplash.com/photo-1568605114967-8130f3a36994?w=1400&q=80&auto=format&fit=crop',
  cabinExt:      'https://images.unsplash.com/photo-1587061949409-02df41d5e562?w=1400&q=80&auto=format&fit=crop',
  cabinInt:      'https://images.unsplash.com/photo-1505693416388-ac5ce068fe85?w=1400&q=80&auto=format&fit=crop',
  veranda:       'https://images.unsplash.com/photo-1521783988139-89397d761dce?w=1400&q=80&auto=format&fit=crop',
  outdoorTable:  'https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=1400&q=80&auto=format&fit=crop',
  // People
  portraitA:     'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=1000&q=80&auto=format&fit=crop',
  portraitB:     'https://images.unsplash.com/photo-1531123897727-8f129e1688ce?w=1000&q=80&auto=format&fit=crop',
  portraitC:     'https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=1000&q=80&auto=format&fit=crop',
  workersField:  'https://images.unsplash.com/photo-1574482620812-13b18c1395f1?w=1400&q=80&auto=format&fit=crop',
  // Misc
  beekeeper:     'https://images.unsplash.com/photo-1587049352846-4a222e784d38?w=1400&q=80&auto=format&fit=crop',
  honey:         'https://images.unsplash.com/photo-1587049352851-8d4e89133924?w=1400&q=80&auto=format&fit=crop',
  borehole:      'https://images.unsplash.com/photo-1559827260-dc66d52bef19?w=1400&q=80&auto=format&fit=crop',
  solar:         'https://images.unsplash.com/photo-1509391366360-2e959784a276?w=1400&q=80&auto=format&fit=crop',
};
window.IMG = IMG;

// ---------- Kinetic background bands ----------
function KineticBands({ words }) {
  // duplicate so the marquee loops seamlessly
  const repeat = (arr) => [...arr, ...arr, ...arr, ...arr];
  return (
    <React.Fragment>
      <div className="band band-1">
        {repeat(words[0]).map((w, i) => <span key={i}>{w}</span>)}
      </div>
      <div className="band band-2 reverse">
        {repeat(words[1]).map((w, i) => <span key={i}>{w}</span>)}
      </div>
      <div className="band band-3">
        {repeat(words[2]).map((w, i) => <span key={i}>{w}</span>)}
      </div>
    </React.Fragment>
  );
}

// ---------- Cycling word ----------
function CyclingWord({ words }) {
  return (
    <span className="kw">
      <span className="kw-track">
        <span className="kw-item">
          {[...words, words[0]].map((w, i) => (
            <span key={i} style={{ display: 'block' }}>{w}</span>
          ))}
        </span>
      </span>
    </span>
  );
}

// ---------- Hero (3 variants) ----------
function Hero({ layout, subBrand, setPage }) {
  const mineralsCopy = {
    eyebrow: 'Mamlakuwth Minerals  /  Mining consultancy',
    headlinePre: 'Unlocking value from Africa’s ',
    cyclingWords: ['tailings.', 'co-products.', 'waste streams.', 'overlooked ore.'],
    lede: 'We help mining companies, developers and investors turn overlooked materials into commercially viable assets — strengthening critical mineral supply chains for the energy transition.',
    metaA: { k: 'Founded', v: '2010' },
    metaB: { k: 'Region', v: 'Sub-Saharan Africa' },
    metaC: { k: 'Specialism', v: 'Processing & re-mining' },
  };
  const landsCopy = {
    eyebrow: 'Mamlakuwth Lands  /  Rehoboth Farm, Selous',
    headlinePre: 'Tending the ground that ',
    cyclingWords: ['feeds.', 'employs.', 'restores.', 'welcomes.'],
    lede: 'A 12.3-hectare working farm at Selous in Mashonaland West — horticulture, greenhouses, broilers, Boer goats and five farm-stay chalets, run as one integrated enterprise.',
    metaA: { k: 'Location', v: 'Selous, Zimbabwe' },
    metaB: { k: 'Footprint', v: '12.3 ha' },
    metaC: { k: 'Enterprises', v: 'Five, integrated' },
  };
  const c = subBrand === 'lands' ? landsCopy : mineralsCopy;

  if (layout === 'split') {
    return (
      <section className={`hero layout-split layout-${layout}`}>
        <KineticBands words={[
          ['Mamlakuwth', 'Minerals', 'Lands', 'Mamlakuwth'],
          ['Zimbabwe', 'Africa', 'Heritage', 'Energy'],
          ['Tailings', 'Harvest', 'Tailings', 'Harvest'],
        ]} />
        <div style={{ position: 'relative', zIndex: 2 }}>
          <div className="eyebrow hero-eyebrow"><span className="dot"></span>{c.eyebrow}</div>
          <h1>
            {c.headlinePre}<CyclingWord words={c.cyclingWords} />
          </h1>
          <p className="hero-lede">{c.lede}</p>
          <div style={{ display: 'flex', gap: 16, marginTop: 40 }}>
            <button className="btn" onClick={() => setPage(subBrand === 'lands' ? 'lands' : 'minerals')}>
              Explore {subBrand === 'lands' ? 'Lands' : 'Minerals'} &rarr;
            </button>
            <button className="btn btn-ghost" onClick={() => setPage('contact')}>
              Start a conversation
            </button>
          </div>
        </div>
        <div className="hero-art ph" style={{ position: 'relative', zIndex: 2 }}>
          <img
            src={subBrand === 'lands' ? IMG.farmField : IMG.oreRocks}
            alt={subBrand === 'lands' ? 'Farm field at golden hour' : 'Ore rock face'}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}
            onError={(e) => { e.target.style.display = 'none'; }}
          />
        </div>
      </section>
    );
  }

  if (layout === 'editorial') {
    return (
      <section className="hero layout-editorial">
        <div style={{ position: 'relative', zIndex: 2, maxWidth: 1480, margin: '0 auto', width: '100%' }}>
          <div className="eyebrow hero-eyebrow"><span className="dot"></span>{c.eyebrow}</div>
          <h1 style={{ maxWidth: '20ch' }}>
            {c.headlinePre}<CyclingWord words={c.cyclingWords} />
          </h1>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--gap-lg)', marginTop: 64, alignItems: 'start' }}>
            <p className="hero-lede" style={{ marginTop: 0 }}>{c.lede}</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'flex-start' }}>
              <button className="btn" onClick={() => setPage(subBrand === 'lands' ? 'lands' : 'minerals')}>
                Explore {subBrand === 'lands' ? 'Lands' : 'Minerals'} &rarr;
              </button>
              <button className="btn btn-ghost" onClick={() => setPage('contact')}>
                Start a conversation
              </button>
            </div>
          </div>
          <div className="hero-meta">
            {[c.metaA, c.metaB, c.metaC].map((m, i) => (
              <div className="hero-meta-item" key={i}>
                <span className="k">{m.k}</span>
                <span className="v">{m.v}</span>
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  // default: kinetic
  return (
    <section className="hero layout-kinetic">
      <KineticBands words={[
        ['Mamlakuwth', 'Minerals', 'Lands', 'Mamlakuwth'],
        ['Zimbabwe', 'Africa', 'Heritage', 'Energy'],
        ['Tailings', 'Harvest', 'Tailings', 'Harvest'],
      ]} />
      <div style={{ position: 'relative', zIndex: 2 }}>
        <div className="eyebrow hero-eyebrow"><span className="dot"></span>{c.eyebrow}</div>
        <h1>
          {c.headlinePre}<CyclingWord words={c.cyclingWords} />
        </h1>
        <p className="hero-lede">{c.lede}</p>
        <div style={{ display: 'flex', gap: 16, marginTop: 40, flexWrap: 'wrap' }}>
          <button className="btn" onClick={() => setPage(subBrand === 'lands' ? 'lands' : 'minerals')}>
            Explore {subBrand === 'lands' ? 'Lands' : 'Minerals'} &rarr;
          </button>
          <button className="btn btn-ghost" onClick={() => setPage('contact')}>
            Start a conversation
          </button>
        </div>
        <div className="hero-meta">
          {[c.metaA, c.metaB, c.metaC].map((m, i) => (
            <div className="hero-meta-item" key={i}>
              <span className="k">{m.k}</span>
              <span className="v">{m.v}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Sub-brand pill ----------
function SubBrandToggle({ value, onChange }) {
  return (
    <div className="subbrand" role="tablist">
      <button className={value === 'minerals' ? 'active' : ''} onClick={() => onChange('minerals')}>Minerals</button>
      <button className={value === 'lands' ? 'active' : ''} onClick={() => onChange('lands')}>Lands</button>
    </div>
  );
}

// ---------- Page header ----------
function PageHead({ crumbs, title, lede, children }) {
  return (
    <header className="page-head page-fade">
      <div className="container">
        <div className="crumbs">{crumbs}</div>
        <h1>{title}</h1>
        {lede && <p>{lede}</p>}
        {children}
      </div>
    </header>
  );
}

// Expose
Object.assign(window, {
  Mark, Nav, Footer, Ph, KineticBands, CyclingWord,
  Hero, SubBrandToggle, PageHead,
});
