/* eslint-disable */
/* global React, ReactDOM, useLang, LangProvider, NavBar, Footer, TeramotMark,
          useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakSelect,
          Press */

const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "variant": "conservative",
  "density": "regular",
  "accent": "#253DE5"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = ['#253DE5', '#5A6DF3', '#0B0F14', '#2436b5'];

/* ───────────────────────── helpers ───────────────────────── */

const prefersReducedMotion = () =>
  typeof window !== 'undefined' &&
  window.matchMedia &&
  window.matchMedia('(prefers-reduced-motion: reduce)').matches;

/* Brand mark, NavBar, Footer live in chrome.jsx — shared across pages. */

const RichH2 = ({ html, className = 'tm-h2' }) =>
  <h2 className={className} dangerouslySetInnerHTML={{ __html: html }} />;

/* ───────────────────────── typewriter ───────────────────────── */

const Typewriter = ({ phrases }) => {
  const [text, setText] = useState('');
  const [idx, setIdx] = useState(0);
  const [phase, setPhase] = useState('writing');
  const reduced = useRef(prefersReducedMotion());
  const prevFirst = useRef(phrases[0]);

  useEffect(() => {
    if (reduced.current) { setText(phrases[0]); return; }
  }, []); // eslint-disable-line

  // When language switches, start erasing immediately
  useEffect(() => {
    if (reduced.current) return;
    if (phrases[0] !== prevFirst.current) {
      prevFirst.current = phrases[0];
      setPhase('deleting');
    }
  }, [phrases]); // eslint-disable-line

  useEffect(() => {
    if (reduced.current) return;
    const current = phrases[idx % phrases.length];
    let timer;
    if (phase === 'writing') {
      if (text.length < current.length) {
        timer = setTimeout(() => setText(current.slice(0, text.length + 1)), 48 + Math.random() * 18);
      } else {
        timer = setTimeout(() => setPhase('holding'), 0);
      }
    } else if (phase === 'holding') {
      timer = setTimeout(() => setPhase('deleting'), 3600);
    } else if (phase === 'deleting') {
      if (text.length > 0) {
        timer = setTimeout(() => setText(text.slice(0, -1)), 26);
      } else {
        setIdx(idx + 1);
        setPhase('writing');
      }
    }
    return () => clearTimeout(timer);
  }, [text, idx, phase, phrases]);

  return (
    <span className="tm-typewriter" aria-hidden="true">
      {text}
      <span className="tm-caret" />
    </span>
  );
};

/* ───────────────────────── hero ───────────────────────── */

const Hero = () => {
  const { c, lang } = useLang();
  const longestPhrase = c.hero.capabilities.reduce((a, b) => (a.length >= b.length ? a : b), '');

  return (
    <section className="tm-hero">
      <div className="tm-hero-motif" aria-hidden="true">
        <span className="tm-motif-pill"></span>
        <span className="tm-motif-disc-a"></span>
        <span className="tm-motif-disc-b"></span>
      </div>
      <div className="tm-container">
        <div className="tm-hero-copy">
          <h1 className="tm-hero-headline">
            {c.hero.headlinePre}{' '}
            <span className="tm-hero-accent">{c.hero.headlineHighlight}</span>{' '}
            {c.hero.headlineBridge}{' '}
            <span className="tm-hero-morph" aria-label={c.hero.srCapabilities}>
              <span className="tm-hero-morph-ghost" aria-hidden="true">{longestPhrase}</span>
              <span className="tm-hero-morph-text">
                <Typewriter phrases={c.hero.capabilities} />
              </span>
            </span>
          </h1>

          <p className="tm-hero-sub">
            {c.hero.sub}
            <span className="tm-hero-sub-em">{c.hero.subHighlight}</span>
            {c.hero.subPost}
          </p>

          <div className="tm-hero-actions">
            <a className="tm-btn tm-btn-dark tm-btn-lg" href={c.links.app}>{c.hero.ctaPrimary}</a>
            <a className="tm-btn tm-btn-ghost tm-btn-lg" href={c.links.call} target="_blank" rel="noopener noreferrer">
              {c.callCta}
              <i className="ph-bold ph-calendar-blank tm-arrow"></i>
            </a>
          </div>
          <div className="tm-cta-meta tm-hero-meta">
            {c.cta.meta.map((m, i) => (
              <span key={i}>
                {i === 0 && <i className="ph-fill ph-shield-check" style={{color: 'var(--accent)', fontSize: '13px'}}></i>}
                {m}
              </span>
            ))}
          </div>
        </div>

        <div className="tm-hero-visual">
          <SchemaDiagram compact />
        </div>
      </div>
    </section>
  );
};

const HeroProofStrip = () => {
  const { c } = useLang();
  return (
    <section className="tm-proofstrip">
      <div className="tm-container">
        <p className="tm-aboveproof-label">{c.proof.label}</p>
        <div className="tm-logos-row" aria-label="Client logos">
          {CLIENT_LOGOS.map(({ name, Cmp }) => (
            <span key={name} title={name} aria-label={name}>
              <Cmp />
            </span>
          ))}
          <span className="tm-logos-more">{c.proof.more}</span>
        </div>
      </div>
    </section>
  );
};

/* ───────────────────────── how it works ───────────────────────── */

const HowItWorks = () => {
  const { c } = useLang();
  return (
    <section className="tm-section" id="how">
      <div className="tm-container">
        <div className="tm-section-head">
          <RichH2 html={c.how.h2html} />
        </div>

        <div className="tm-steps">
          {c.how.steps.map((s, i) => (
            <div key={i} className="tm-step">
              <div className="tm-step-num">0{i + 1}</div>
              <h3 className="tm-step-title">{s.title}</h3>
              <p className="tm-step-body">{s.body}</p>
              <span className="tm-step-tag">
                <i className="ph-fill ph-shield-check"></i>{s.tag}
              </span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ───────────────────────── no effort ───────────────────────── */

const NoEffort = () => {
  const { c } = useLang();
  return (
    <section className="tm-section" id="effort">
      <div className="tm-container">
        <div className="tm-two-col">
          <div>
            <RichH2 html={c.effort.h2html} />
          </div>

          <div className="tm-compare" role="table" aria-label="Comparison">
            <div className="tm-compare-grid">
              <div className="tm-compare-col">
                <p className="tm-compare-head">{c.effort.compareLeft.head}</p>
                <ul className="tm-compare-list">
                  {c.effort.compareLeft.items.map((it, i) => (
                    <li key={i}>
                      <span className="tm-x" aria-hidden="true"><i className="ph-bold ph-x"></i></span>
                      {it}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="tm-compare-col">
                <p className="tm-compare-head">{c.effort.compareRight.head}</p>
                <ul className="tm-compare-list">
                  {c.effort.compareRight.items.map((it, i) => (
                    <li key={i}>
                      <span className="tm-check" aria-hidden="true"><i className="ph-bold ph-check"></i></span>
                      {it}
                    </li>
                  ))}
                </ul>
              </div>
            </div>
            <div className="tm-compare-footer">{c.effort.footer}</div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ───────────────────────── security ───────────────────────── */

const Security = () => {
  const { c } = useLang();
  return (
    <section className="tm-section" id="security">
      <div className="tm-container">
        <div className="tm-two-col is-reversed">
          <div className="tm-sec">
            <div className="tm-sec-header">
              <span className="tm-sec-badge" aria-hidden="true">
                <i className="ph-fill ph-shield-check"></i>
              </span>
              <div className="tm-sec-headtext">
                <h3 className="tm-sec-headtitle">{c.security.cardTitle}</h3>
                <p className="tm-sec-headsub">{c.security.cardSub}</p>
              </div>
            </div>
            <div className="tm-sec-row">
              <span className="tm-sec-ico"><i className="ph ph-cloud-arrow-up"></i></span>
              <div>
                <h4 className="tm-sec-rowtitle">{c.security.optTitle1}</h4>
                <p className="tm-sec-rowbody">{c.security.optBody1}</p>
              </div>
            </div>
            <div className="tm-sec-row">
              <span className="tm-sec-ico"><i className="ph ph-lock-key"></i></span>
              <div>
                <h4 className="tm-sec-rowtitle">{c.security.optTitle2}</h4>
                <p className="tm-sec-rowbody">{c.security.optBody2}</p>
              </div>
            </div>
          </div>

          <div>
            <RichH2 html={c.security.h2html} />
          </div>
        </div>
      </div>
    </section>
  );
};

/* ───────────────────────── audience ───────────────────────── */

const Audience = () => {
  const { c } = useLang();
  return (
    <section className="tm-section" id="audience">
      <div className="tm-container">
        <RichH2 html={c.audience.h2html} />
        <div className="tm-audience-chips">
          {c.audience.chips.map((chip, i) => (
            <span key={i} className="tm-chip">{chip}</span>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ───────────────────────── cta final ───────────────────────── */

const CtaFinal = () => {
  const { c } = useLang();
  return (
    <section className="tm-cta" id="start">
      <div className="tm-container">
        <h2 className="tm-cta-h2">
          {c.cta.line1}
          <span className="tm-cta-line2">{c.cta.line2}</span>
        </h2>
        <div className="tm-cta-actions">
          <a className="tm-btn tm-btn-dark tm-btn-lg" href={c.links.app}>
            {c.cta.button}
            <i className="ph-bold ph-arrow-right"></i>
          </a>
          <a className="tm-btn tm-btn-ghost tm-btn-lg" href={c.links.call} target="_blank" rel="noopener noreferrer">
            {c.callCta}
            <i className="ph-bold ph-calendar-blank"></i>
          </a>
        </div>
        <div className="tm-cta-meta">
          {c.cta.meta.map((m, i) => (
            <span key={i}>
              {i === 0 && <i className="ph-fill ph-shield-check" style={{color: 'var(--accent)', fontSize: '13px'}}></i>}
              {m}
            </span>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ───────────────────────── app + tweaks ───────────────────────── */

const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks to <body> attributes + CSS vars
  useEffect(() => {
    document.body.setAttribute('data-variant', t.variant);
    document.body.setAttribute('data-density', t.density);
    document.body.style.setProperty('--accent', t.accent);
    document.body.style.setProperty(
      '--accent-soft',
      `color-mix(in oklab, ${t.accent} 14%, transparent)`
    );
  }, [t.variant, t.density, t.accent]);

  return (
    <LangProvider>
      <NavBar current="home" />
      <main>
        <Hero />
        <HeroProofStrip />
        <Features />
        <HowItWorks />
        <NoEffort />
        <Security />
        <Audience />
        <Press />
        <CtaFinal />
      </main>
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Variant" />
        <TweakRadio
          label="Style"
          value={t.variant}
          options={['conservative', 'bold']}
          onChange={(v) => setTweak('variant', v)}
        />
        <TweakRadio
          label="Density"
          value={t.density}
          options={['compact', 'regular', 'relaxed']}
          onChange={(v) => setTweak('density', v)}
        />

        <TweakSection label="Accent" />
        <TweakColor
          label="Color"
          value={t.accent}
          options={ACCENT_OPTIONS}
          onChange={(v) => setTweak('accent', v)}
        />
      </TweaksPanel>
    </LangProvider>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
