const { useEffect, useState } = React;
const { Button, Badge, Dialog, Input, Checkbox } = window.IOptusDesignSystem_ff608d;
const I = window.IOptusIcons;
const LOGO = 'assets/logos/';
const HOME = '/';
const PAGES = { products: '/products', about: '/about', news: '/news', contact: '/contact', privacy: '/privacy-notice', terms: '/terms-and-conditions', cookies: '/cookie-policy', slavery: '/modern-slavery-statement', appeula: '/app-eula', appprivacy: '/app-privacy-notice' };

function useReveal() {
  useEffect(() => {
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.1 });
    document.querySelectorAll('.reveal').forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ============================ NAV ============================ */
function Nav() {
  const cur = document.body.dataset.page || 'home';
  const links = [['Home', HOME, 'home'], ['Products', PAGES.products, 'products'], ['About', PAGES.about, 'about'], ['News', PAGES.news, 'news'], ['Contact', PAGES.contact, 'contact']];
  return (
    <React.Fragment>
    <header style={{ position: 'sticky', top: 0, zIndex: 60, background: 'rgba(255,255,255,0.9)', backdropFilter: 'blur(12px)', borderBottom: '1px solid var(--p100)' }}>
      <div className="wrap" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 88, gap: 24 }}>
        <a href={HOME} style={{ display: 'flex' }}><img src={LOGO + 'iOptus.png'} alt="iOptus" style={{ height: 42 }} /></a>
        <nav className="navlinks" style={{ display: 'flex', gap: 30 }}>
          {links.map(([l, h, k]) => <a key={l} href={h} aria-current={cur === k ? 'page' : undefined} style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 15.5, color: cur === k ? 'var(--p900)' : 'var(--p600)', borderBottom: cur === k ? '2px solid var(--p500)' : '2px solid transparent', paddingBottom: 2 }}>{l}</a>)}
        </nav>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <Button size="sm" iconRight={<I.ChevronRight size={16} />} onClick={() => openDemo()}>Book a demo</Button>
        </div>
      </div>
    </header>
    <DemoModal />
    </React.Fragment>
  );
}

/* ============================ DEMO MODAL ============================ */
const DEMO_PRODUCTS = [['OptusEcho', 'var(--blue-400)'], ['Empient', 'var(--yellow-400)'], ['OptusApp', 'var(--coral-500)']];
let _openDemo = null;
function openDemo(preset) { if (_openDemo) _openDemo(preset || []); }
function DemoModal() {
  const blank = { name: '', email: '', phone: '', prods: [] };
  const [open, setOpen] = useState(false);
  const [f, setF] = useState(blank);
  const [err, setErr] = useState({});
  const [sent, setSent] = useState(false);
  useEffect(() => { _openDemo = (preset) => { setF({ ...blank, prods: preset }); setErr({}); setSent(false); setOpen(true); }; return () => { _openDemo = null; }; }, []);
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const toggle = (p) => setF({ ...f, prods: f.prods.includes(p) ? f.prods.filter((x) => x !== p) : [...f.prods, p] });
  const submit = (e) => {
    e.preventDefault();
    const n = {};
    if (!f.name.trim()) n.name = 'Please enter your name';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email)) n.email = 'Please enter a valid email address';
    if (!f.prods.length) n.prods = 'Pick at least one product';
    setErr(n);
    if (!Object.keys(n).length) { window.__sendForm("demo", f).then(() => setSent(true)).catch((er) => setErr({ email: er.message })); }
  };
  const close = () => setOpen(false);
  if (sent) return (
    <Dialog open={open} onClose={close} title="Demo requested" width={480} footer={<Button onClick={close}>Done</Button>}>
      <p style={{ fontSize: 15.5, color: 'var(--p600)', lineHeight: 1.6 }}>Thanks, {f.name.split(' ')[0]}. We’ll email <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--p900)' }}>{f.email}</span> within one working day to arrange a 30-minute demo of {f.prods.join(', ')}.</p>
    </Dialog>
  );
  return (
    <Dialog open={open} onClose={close} title="Book a demo" width={520} footer={<React.Fragment><Button variant="ghost" onClick={close}>Cancel</Button><Button form="demo-form" type="submit" iconRight={<I.ChevronRight size={17} />}>Request demo</Button></React.Fragment>}>
      <form id="demo-form" onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <p style={{ fontSize: 14.5, color: 'var(--p500)', lineHeight: 1.55, marginTop: -4 }}>30 minutes, no slides. We’ll show you the products and tell you honestly if we’re the right fit.</p>
        <Input label="Name" required value={f.name} onChange={set('name')} error={err.name} autoComplete="name" />
        <Input label="Email" type="email" required value={f.email} onChange={set('email')} error={err.email} autoComplete="email" />
        <Input label="Phone" type="tel" value={f.phone} onChange={set('phone')} helper="Optional" autoComplete="tel" />
        <div>
          <span style={{ display: 'block', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', fontWeight: 'var(--fw-medium)', color: 'var(--text-strong)', marginBottom: 8 }}>Which products?<span style={{ color: 'var(--status-danger)', marginLeft: 2 }}>*</span></span>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
            {DEMO_PRODUCTS.map(([p, dot]) => { const a = f.prods.includes(p); return (
              <button key={p} type="button" aria-pressed={a} onClick={() => toggle(p)} style={{ cursor: 'pointer', textAlign: 'left', padding: '12px 12px', borderRadius: 12, border: '1.5px solid ' + (a ? 'var(--p500)' : 'var(--border-default)'), background: a ? 'var(--p50)' : '#fff', fontFamily: 'var(--font-display)', transition: 'all .15s cubic-bezier(0.2,0,0,1)', boxShadow: a ? 'var(--shadow-focus)' : 'none' }}>
                <span style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: dot }} />{a && <I.Check size={14} color="var(--p600)" />}</span>
                <span style={{ fontWeight: 600, fontSize: 13.5, color: a ? 'var(--p900)' : 'var(--p600)' }}>{p}</span>
              </button>); })}
          </div>
          <p style={{ fontSize: 'var(--fs-xs)', color: err.prods ? 'var(--status-danger)' : 'var(--text-muted)', marginTop: 6 }}>{err.prods || 'Pick one, two or all three.'}</p>
        </div>
        <p style={{ fontSize: 12.5, color: 'var(--p400)', lineHeight: 1.5 }}>By requesting a demo you agree to us contacting you about your enquiry. See our <a href={PAGES.privacy}>privacy notice</a>.</p>
      </form>
    </Dialog>
  );
}

/* ============================ HERO ============================ */
function Hero() {
  return (
    <section id="top" style={{ position: 'relative', overflow: 'hidden', borderBottom: '1px solid var(--p100)' }}>
      <div className="dotfield" aria-hidden="true"></div>
      <div className="wrap" style={{ position: 'relative' }}>
        <div className="herogrid" style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center', paddingTop: 84, paddingBottom: 84 }}>
          <div style={{ paddingLeft: 24 }}>
            <h1 className="reveal in" style={{ fontSize: 'clamp(34px,4.15vw,54px)', fontWeight: 700, lineHeight: 1.02, letterSpacing: '-0.035em' }}>Housing software you can <span style={{ color: 'var(--p500)' }}>rely on</span> — every call, every case, every day.</h1>
            <p className="reveal in" style={{ fontSize: 18, lineHeight: 1.62, color: 'var(--p600)', marginTop: 22, maxWidth: 480 }}>Three products for tenants, housing teams and the people who answer the phone — each complete on its own, natively integrated when you use more than one. Secure, UK & EU-hosted, supported by real people.</p>
            <div className="reveal in" style={{ display: 'flex', gap: 12, marginTop: 30, flexWrap: 'wrap' }}>
              <Button size="lg" iconRight={<I.ChevronRight size={19} />} onClick={() => openDemo()}>Book a demo</Button>
              <Button size="lg" variant="outline" onClick={() => { const el = document.getElementById('products'); window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 68, behavior: 'smooth' }); }}>See the products</Button>
            </div>
          </div>
          <Console />
        </div>
      </div>
    </section>
  );
}

const CORAL = 'var(--coral-500)', BLUE = 'var(--blue-400)', YEL = 'var(--yellow-400)';
const PICK_LINES = {
  '': 'Each product stands alone. Together, they share the work.',
  'OptusApp': 'Tenants report, pay and message from their phone. Works alongside your existing housing system.',
  'OptusEcho': 'AI voice agents answer every call, in housing or any other sector, and hand over to your team when it matters.',
  'Empient': 'Cases, repairs, assets and CRM for housing teams — complete on its own.',
  'OptusApp+OptusEcho': 'A call to OptusEcho becomes a tracked repair the tenant can follow in OptusApp — nothing entered twice.',
  'Empient+OptusApp': 'Every case in Empient shows up for the tenant in OptusApp, with live status updates.',
  'Empient+OptusEcho': 'OptusEcho raises and updates Empient cases directly from the call.',
  'Empient+OptusApp+OptusEcho': 'Call, case and tenant update flow through all three automatically.',
};
function Console() {
  const [on, setOn] = useState({ OptusApp: false, OptusEcho: false, Empient: false });
  const [auto, setAuto] = useState(true);
  const prods = [['OptusEcho', BLUE, 'PhoneCall'], ['Empient', YEL, 'Home'], ['OptusApp', CORAL, 'Smartphone']];
  React.useEffect(() => {
    if (!auto || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const names = prods.map(([n]) => n);
    // bits: 1 OptusEcho, 2 Empient, 4 OptusApp. None → singles → pre-shuffled pairs/all → back to none
    const SEQ = [0, 1, 2, 4, 6, 7, 5, 3];
    let idx = 0;
    const step = () => {
      idx = (idx + 1) % SEQ.length;
      const m = SEQ[idx];
      setOn(Object.fromEntries(names.map((n, i) => [n, !!(m & (1 << i))])));
    };
    const t0 = setTimeout(step, 1200);
    const iv = setInterval(step, 3200);
    return () => { clearTimeout(t0); clearInterval(iv); };
  }, [auto]);
  const sel = prods.filter(([n]) => on[n]).map(([n]) => n);
  const key = sel.slice().sort().join('+');
  const glass = { background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 12 };
  return (
    <div className="reveal in" style={{ borderRadius: 22, background: 'linear-gradient(135deg, var(--purple-600), var(--purple-800))', padding: 22, boxShadow: '0 30px 60px -28px var(--p700)', color: '#fff', display: 'flex', flexDirection: 'column', minHeight: 420 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
        <span className="kick" style={{ color: 'var(--p200)' }}>Use one, or all together</span>
        <span className="kick tick" style={{ color: 'var(--p300)' }}>{sel.length} of 3 selected</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
        {prods.map(([n, dot, ic]) => { const Ic = I[ic]; const a = on[n]; return (
          <button key={n} type="button" aria-pressed={a} onClick={() => { if (auto) { setAuto(false); setOn({ OptusApp: false, OptusEcho: false, Empient: false, [n]: true }); } else setOn({ ...on, [n]: !a }); }} style={{ ...glass, cursor: 'pointer', color: '#fff', padding: '16px 14px', textAlign: 'left', background: a ? '#fff' : 'rgba(255,255,255,0.04)', borderColor: a ? '#fff' : 'rgba(255,255,255,0.1)', boxShadow: a ? '0 10px 24px -12px rgba(23,21,42,0.6)' : 'none', transition: 'all .2s cubic-bezier(0.2,0,0,1)', fontFamily: 'var(--font-display)' }}>
            <span style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}><Ic size={18} color={a ? 'var(--p600)' : '#fff'} style={{ transition: 'color .2s' }} /><span style={{ width: 8, height: 8, borderRadius: '50%', background: a ? dot : 'rgba(255,255,255,0.2)' }} /></span>
            <img src={LOGO + n + '.png'} alt={n} style={{ display: 'block', height: 15, maxWidth: '100%', objectFit: 'contain', objectPosition: 'left', filter: a ? 'none' : 'brightness(0) invert(1)', opacity: a ? 1 : 0.6, transition: 'opacity .2s' }} />
          </button>); })}
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '22px 4px' }}>
        <span className="kick" style={{ color: 'var(--p300)', marginBottom: 10 }}>{sel.length > 1 ? 'Natively integrated' : sel.length === 1 ? 'Complete on its own' : 'Pick a product'}</span>
        <p key={key} className="fadein" style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 19, lineHeight: 1.35, letterSpacing: '-0.01em' }}>{PICK_LINES[key]}</p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
        {[['Products', String(sel.length)], ['Integrations', String(sel.length * (sel.length - 1) / 2)], ['Data entered twice', '0']].map(([l, v]) => (
          <div key={l} style={{ ...glass, padding: '12px 14px' }}>
            <div className="tick" style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, letterSpacing: '-0.03em' }}>{v}</div>
            <p style={{ fontSize: 12, color: 'var(--p300)', marginTop: 4 }}>{l}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============================ TRUST STRIP ============================ */
function Trust() {
  const items = [['Flag', 'UK & EU-hosted', 'Data stays in the UK & EU'], ['Lock', 'GDPR-ready', 'Privacy by design'], ['Grid', 'System agnostic', 'Integrates with what you run'], ['Message', 'Support you can reach', 'And a team you know']];
  return (
    <section style={{ borderBottom: '1px solid var(--p100)' }}>
      <div className="wrap trust reveal" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)' }}>
        {items.map(([ic, t, d], i) => {
          const Ic = I[ic] || I.Check;
          return (
            <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '22px 24px', borderLeft: i ? '1px solid var(--p100)' : 'none' }}>
              <span style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--p50)', border: '1px solid var(--p100)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic size={17} color="var(--p600)" /></span>
              <div><div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14.5, color: 'var(--p900)' }}>{t}</div><p style={{ fontSize: 12.5, color: 'var(--p400)', marginTop: 2 }}>{d}</p></div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

/* ============================ PAGE HEADER ============================ */
function PageHead({ kick, title, lede, children }) {
  return (
    <section style={{ position: 'relative', overflow: 'hidden', borderBottom: '1px solid var(--p100)' }}>
      <div className="dotfield" aria-hidden="true"></div>
      <div className="wrap" style={{ position: 'relative' }}>
        <div style={{ position: 'relative', padding: '72px 24px 64px', maxWidth: 760 }}>
          {kick && <p className="kick reveal in" style={{ marginBottom: 18 }}>{kick}</p>}
          <h1 className="reveal in" style={{ fontSize: 'clamp(36px,4.4vw,58px)', fontWeight: 700, lineHeight: 1.04, letterSpacing: '-0.035em' }}>{title}</h1>
          {lede && <p className="reveal in" style={{ fontSize: 18, lineHeight: 1.62, color: 'var(--p600)', marginTop: 20, maxWidth: 600 }}>{lede}</p>}
          {children}
        </div>
      </div>
    </section>
  );
}

/* ============================ FOOTER ============================ */
function Footer() {
  const cols = [['Products', [['OptusEcho', PAGES.products + '#optusecho'], ['Empient', PAGES.products + '#empient'], ['OptusApp', PAGES.products + '#optusapp']]], ['Company', [['About us', PAGES.about], ['News', PAGES.news], ['Contact', PAGES.contact]]], ['Legal', [['Privacy notice', PAGES.privacy], ['Terms and conditions', PAGES.terms], ['Cookie policy', PAGES.cookies], ['Modern slavery statement', PAGES.slavery], ['App EULA', PAGES.appeula], ['App privacy notice', PAGES.appprivacy]]]];
  return (
    <footer style={{ paddingBottom: 40, borderTop: '1px solid var(--p100)' }}>
      <div className="wrap">
        <div className="fgrid" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', gap: 40, padding: '52px 0 34px' }}>
          <div>
            <img src={LOGO + 'iOptus.png'} alt="iOptus" style={{ height: 26 }} />
            <p style={{ fontSize: 14, color: 'var(--p500)', marginTop: 16, lineHeight: 1.55, maxWidth: 250 }}>Good, clean software that grows with you rather than making you grow with it.</p>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 7, marginTop: 14, fontSize: 13.5, color: 'var(--p500)', lineHeight: 1.5 }}><I.MapPin size={15} color="var(--p400)" style={{ marginTop: 3, flexShrink: 0 }} /><span>Quadrant House, Broad St Mall,<br />Reading, RG1 7QE</span></div>
          </div>
          {cols.map(([h, links]) => (
            <div key={h}>
              <h4 className="kick" style={{ marginBottom: 16 }}>{h}</h4>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {links.map(([l, href]) => <li key={l}><a href={href} style={{ fontSize: 14, color: 'var(--p600)' }}>{l}</a></li>)}
                {h === 'Legal' && <li><a href="#" onClick={(e) => { e.preventDefault(); window.openCookieSettings && window.openCookieSettings(); }} style={{ fontSize: 14, color: 'var(--p600)' }}>Cookie settings</a></li>}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ borderTop: '1px solid var(--p100)', paddingTop: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <span style={{ fontSize: 13, color: 'var(--p400)' }}>© 2026 Optus Homes Ltd (T/A iOptus). Registered in England &amp; Wales, no. 12429269.</span>
          <div style={{ display: 'flex', gap: 22 }}>{[['Privacy', PAGES.privacy], ['Terms', PAGES.terms], ['Cookies', PAGES.cookies]].map(([l, h]) => <a key={l} href={h} style={{ fontSize: 13, color: 'var(--p400)' }}>{l}</a>)}<a href="#" onClick={(e) => { e.preventDefault(); window.openCookieSettings && window.openCookieSettings(); }} style={{ fontSize: 13, color: 'var(--p400)', display: 'inline-flex', alignItems: 'center', gap: 6 }}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5"/><path d="M8.5 8.5v.01"/><path d="M16 15.5v.01"/><path d="M12 12v.01"/><path d="M11 17v.01"/><path d="M7 14v.01"/></svg>Cookie settings</a></div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Trust, Footer, PageHead, useReveal, openDemo, LOGO, HOME, PAGES });
