/* =====================================================================
   Future Consulting — Homepage React app
   ===================================================================== */

const { useState, useEffect } = React;

/* Tweaks — defaults persisted via __edit_mode_set_keys */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "auto",
  "accent": "mint",
  "density": "spacious"
}/*EDITMODE-END*/;

const ACCENTS = {
  mint:  { mint: '#85E6C6', bright: '#A8F0D4', deep: '#4FC9A1', glow: 'rgba(133, 230, 198, 0.40)', soft: 'rgba(133, 230, 198, 0.08)' },
  cyan:  { mint: '#7BD7F0', bright: '#A8E8F8', deep: '#4FB3D4', glow: 'rgba(123, 215, 240, 0.40)', soft: 'rgba(123, 215, 240, 0.08)' },
  steel: { mint: '#9CB5D6', bright: '#BFD3EE', deep: '#6B8FB8', glow: 'rgba(156, 181, 214, 0.40)', soft: 'rgba(156, 181, 214, 0.08)' },
};

function useApplyAccent(name) {
  useEffect(() => {
    const a = ACCENTS[name] || ACCENTS.mint;
    const r = document.documentElement;
    r.style.setProperty('--mint', a.mint);
    r.style.setProperty('--mint-bright', a.bright);
    r.style.setProperty('--mint-deep', a.deep);
    r.style.setProperty('--mint-glow', a.glow);
    r.style.setProperty('--mint-soft', a.soft);
    r.style.setProperty('--line-mint', `${a.mint}4D`);
    r.style.setProperty('--shadow-mint', `0 0 40px -8px ${a.mint}59`);
  }, [name]);
}

function Reveal({ children, className = '', stagger = false, ...rest }) {
  const ref = useReveal();
  return (
    <div ref={ref} className={(stagger ? 'reveal-stagger ' : 'reveal ') + className} {...rest}>
      {children}
    </div>
  );
}

/* ================== HERO ================== */
function Hero({ variant }) {
  const { t } = useI18n();
  const titleLines = variant === 'orbital' ? t.hero.titleA : t.hero.titleB;
  const isAuto = variant === 'auto';
  const [autoCurrent, setAutoCurrent] = useState('orbital');

  useEffect(() => {
    if (!isAuto) return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) return;
    const id = setInterval(() => {
      setAutoCurrent((c) => (c === 'orbital' ? 'network' : 'orbital'));
    }, 5000);
    return () => clearInterval(id);
  }, [isAuto]);

  const activeVisual = isAuto ? autoCurrent : variant;

  return (
    <section className="hero">
      <div className="grid-bg"/>
      <div className="container hero-inner">
        <div className="hero-text">
          <div className="hero-eyebrow"><span className="eyebrow">{t.hero.eyebrow}</span></div>
          <h1 className="hero-title">
            {titleLines.map((line, i) => (
              <span key={i} className="line">
                {i === titleLines.length - 1 ? <span className="accent">{line}</span> : line}
              </span>
            ))}
          </h1>
          <p className="hero-sub">{t.hero.sub}</p>
          <div className="hero-cta">
            <a href="kapcsolat.html" className="btn btn-primary btn-lg">
              {t.hero.ctaPrimary}<ArrowRight size={16}/>
            </a>
            <a href="fusion.html" className="btn btn-ghost btn-lg">
              {t.hero.ctaSecondary}<ArrowUpRight size={16}/>
            </a>
          </div>

          <div className="hero-values">
            {t.hero.values.map((v, i) => {
              const Icon = [Activity, Spark, Layers][i] || Spark;
              return (
                <div className="hero-value" key={i}>
                  <div className="hero-value-icon"><Icon size={18}/></div>
                  <div className="hero-value-title">{v.title}</div>
                  <div className="hero-value-desc">{v.desc}</div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="hero-visual">
          <div className={"hero-visual-layer " + (activeVisual === 'orbital' ? 'on' : '')} aria-hidden={activeVisual !== 'orbital'}>
            <OrbitalHero/>
          </div>
          <div className={"hero-visual-layer " + (activeVisual === 'network' ? 'on' : '')} aria-hidden={activeVisual !== 'network'}>
            <NetworkHero/>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================== HERO PROOF STRIP ================== */
/* Anchoring + social proof a hero alatt — valós, anonim számok. */
function HeroProofStrip() {
  const { t } = useI18n();
  const hp = t.heroProof;
  return (
    <section className="hero-proof">
      <div className="container">
        <div className="hero-proof-grid">
          {hp.items.map((it, i) => (
            <div className="hero-proof-item" key={i}>
              <div className="hero-proof-num">{it.num}</div>
              <div className="hero-proof-label">{it.label}</div>
            </div>
          ))}
        </div>
        <p className="hero-proof-tagline">{hp.tagline}</p>
      </div>
    </section>
  );
}

/* ================== FUSION MODEL ================== */
/* Felváltja a régi TrustSection-t ÉS a régi FusionSection-t (a főoldalon).
   3 capability-card (AI · IT · AV) + 4 érték-attribútum a sávban alul. */
function FusionModelSection() {
  const { t } = useI18n();
  const fm = t.fusionModel;
  const pillarIcons = [Spark, Layers, Globe];
  const attrIcons = [Network, Activity, Server, Compass];
  return (
    <section className="section fusion-model-section">
      <div className="container">
        <div className="fm-grid">
          <Reveal>
            <div className="fm-intro">
              <div className="eyebrow">{fm.eyebrow}</div>
              <h2 className="h-2" style={{marginTop: 16, marginBottom: 16}}>{fm.title}</h2>
              <p className="lead">{fm.desc}</p>
            </div>
          </Reveal>
          <Reveal>
            <div className="fm-pillars">
              {fm.pillars.map((p, i) => {
                const Icon = pillarIcons[i] || Spark;
                return (
                  <div className="fm-pillar" key={p.label}>
                    <div className="fm-pillar-icon"><Icon size={28}/></div>
                    <div className="fm-pillar-label">{p.label}</div>
                    <div className="fm-pillar-title">{p.title}</div>
                    <ul className="fm-pillar-items">
                      {p.items.map((it) => <li key={it}>{it}</li>)}
                    </ul>
                  </div>
                );
              })}
            </div>
          </Reveal>
        </div>
        <Reveal>
          <div className="fm-attrs">
            {fm.attributes.map((a, i) => {
              const Icon = attrIcons[i] || Spark;
              return (
                <div className="fm-attr" key={a.title}>
                  <div className="fm-attr-icon"><Icon size={20}/></div>
                  <div>
                    <div className="fm-attr-title">{a.title}</div>
                    <div className="fm-attr-desc">{a.desc}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ================== SERVICES STRIP ================== */
/* Felváltja a régi 6-pillér-card ServicesSection-t — minimal, csak nevek a Fusion Model alatt.
   A részletek a services.html aloldalon. */
function ServicesStrip() {
  const { t } = useI18n();
  return (
    <section className="section services-strip-section" id="services">
      <div className="container">
        <Reveal>
          <div className="services-strip-head">
            <div className="eyebrow">{t.services.eyebrow}</div>
            <a href="services.html" className="btn btn-ghost btn-sm">
              {t.common.learnMore}<ArrowUpRight size={14}/>
            </a>
          </div>
        </Reveal>
        <Reveal>
          <div className="services-strip">
            {t.services.pillars.map((p) => (
              <a href="services.html" className="services-strip-item" key={p.tag}>
                <span className="services-strip-num">{p.tag}</span>
                <span className="services-strip-title">{p.title}</span>
                <ArrowUpRight className="services-strip-arrow" size={14}/>
              </a>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ================== AI ================== */
function AISection() {
  const { t } = useI18n();
  return (
    <section className="section ai-section" id="ai">
      <div className="container">
        <div className="ai-grid">
          <Reveal>
            <div>
              <div className="eyebrow">{t.ai.eyebrow}</div>
              <h2 className="h-2" style={{marginTop: 16, marginBottom: 24}}>{t.ai.title}</h2>
              <p className="lead">{t.ai.desc}</p>
            </div>
          </Reveal>
          <Reveal>
            <div className="ai-points">
              {t.ai.points.map((pt, i) => (
                <div className="ai-point" key={i}>
                  <div className="ai-point-num">/0{i + 1}</div>
                  <div>
                    <div className="ai-point-label">{pt.label}</div>
                    <p className="ai-point-desc">{pt.desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ================== CASES ================== */
function CasesSection() {
  const { t } = useI18n();
  return (
    <section className="section" id="cases">
      <div className="container">
        <Reveal>
          <div className="section-head-row">
            <div className="section-head">
              <div className="eyebrow">{t.cases.eyebrow}</div>
              <h2 className="h-2">{t.cases.title}</h2>
              <p className="lead">{t.cases.desc}</p>
            </div>
            <a href="cases.html" className="btn btn-ghost">
              {t.common.learnMore}<ArrowUpRight size={14}/>
            </a>
          </div>
        </Reveal>
        <Reveal>
          <div className="case-grid">
            {t.casesPage.slots.slice(0, 3).map((s, i) => (
              <div className="case-card" key={i}>
                <div className="case-placeholder-tag">
                  <Plus size={11}/>{t.cases.placeholder} 0{i + 1}
                </div>
                <div className="case-industry">{s.ind} · {s.svc}</div>
                <h3 className="case-title">{s.title}</h3>
                <p className="case-desc">{s.desc}</p>
                <div className="case-rows">
                  <div className="case-row"><span className="case-row-key">{t.cases.industry}</span><span className="case-row-val">{s.ind}</span></div>
                  <div className="case-row"><span className="case-row-key">{t.cases.transformation}</span><span className="case-row-val">{s.systems}</span></div>
                  <div className="case-row"><span className="case-row-key">{t.cases.outcome}</span><span className="case-row-val mint">{s.outcome}</span></div>
                </div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ================== CTA — kapcsolatfelvételi form ================== */
function CTASection() {
  const { t } = useI18n();
  const f = t.form;
  const [form, setForm] = useState({ name: "", email: "", company: "", message: "", gdpr: false });
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error

  const onChange = (key) => (e) => {
    const val = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    setForm((s) => ({ ...s, [key]: val }));
    if (errors[key]) setErrors((er) => ({ ...er, [key]: null }));
  };

  const validate = () => {
    const er = {};
    if (!form.name.trim()) er.name = f.required;
    if (!form.email.trim()) er.email = f.required;
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) er.email = f.invalidEmail;
    if (!form.message.trim()) er.message = f.required;
    if (!form.gdpr) er.gdpr = f.required;
    setErrors(er);
    return Object.keys(er).length === 0;
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setStatus("sending");
    try {
      const res = await fetch('/send.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          company: form.company,
          message: form.message,
          gdpr: form.gdpr,
          _gotcha: '',
        }),
      });
      const json = await res.json().catch(() => ({ ok: false, error: 'parse_error' }));
      if (json.ok) {
        setStatus('sent');
      } else if (json.errors) {
        setErrors(json.errors);
        setStatus('idle');
      } else {
        setStatus('error');
      }
    } catch (err) {
      setStatus('error');
    }
  };

  if (status === "sent") {
    return (
      <section className="cta-section" id="contact">
        <div className="container">
          <Reveal>
            <div className="cta-card form-success">
              <div className="form-success-icon">
                <Check size={36}/>
              </div>
              <h2 className="cta-title">{f.success.title}</h2>
              <p className="cta-desc">{f.success.desc}</p>
            </div>
          </Reveal>
        </div>
      </section>
    );
  }

  return (
    <section className="cta-section" id="contact">
      <div className="container">
        <Reveal>
          <div className="cta-card form-card">
            <div className="form-head">
              <div className="eyebrow">{f.eyebrow}</div>
              <h2 className="cta-title">{f.title}</h2>
              <p className="cta-desc">{f.desc}</p>
            </div>

            <form className="contact-form" onSubmit={onSubmit} noValidate>
              <div className="form-row">
                <label className="form-field">
                  <span className="form-label">{f.name.label}</span>
                  <input
                    type="text"
                    value={form.name}
                    onChange={onChange("name")}
                    placeholder={f.name.placeholder}
                    className={errors.name ? "form-input has-error" : "form-input"}
                    required
                  />
                  {errors.name && <span className="form-error">{errors.name}</span>}
                </label>
                <label className="form-field">
                  <span className="form-label">{f.email.label}</span>
                  <input
                    type="email"
                    value={form.email}
                    onChange={onChange("email")}
                    placeholder={f.email.placeholder}
                    className={errors.email ? "form-input has-error" : "form-input"}
                    required
                  />
                  {errors.email && <span className="form-error">{errors.email}</span>}
                </label>
              </div>

              <label className="form-field">
                <span className="form-label">
                  {f.company.label} <span className="form-optional">{f.company.optional}</span>
                </span>
                <input
                  type="text"
                  value={form.company}
                  onChange={onChange("company")}
                  placeholder={f.company.placeholder}
                  className="form-input"
                />
              </label>

              <label className="form-field">
                <span className="form-label">{f.message.label}</span>
                <textarea
                  value={form.message}
                  onChange={onChange("message")}
                  placeholder={f.message.placeholder}
                  className={errors.message ? "form-input form-textarea has-error" : "form-input form-textarea"}
                  rows={3}
                  required
                />
                {errors.message && <span className="form-error">{errors.message}</span>}
              </label>

              <label className={"form-checkbox " + (errors.gdpr ? "has-error" : "")}>
                <input
                  type="checkbox"
                  checked={form.gdpr}
                  onChange={onChange("gdpr")}
                />
                <span className="form-checkbox-text">
                  {f.gdpr} <a href={f.gdprLink.href} target="_blank" rel="noopener">{f.gdprLink.label}</a>
                </span>
              </label>

              <div className="form-submit-wrap">
                <button type="submit" className="btn btn-primary btn-lg" disabled={status === "sending"}>
                  {status === "sending" ? f.sending : f.submit}
                  {status !== "sending" && <ArrowRight size={16}/>}
                </button>
                <span className="meta">{t.cta.sub}</span>
              </div>

              {status === "error" && <p className="form-error-banner">{f.error}</p>}
            </form>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ================== TWEAKS PANEL ================== */
function HomeTweaks({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Hero">
        <TweakRadio label="Hero variation"
          value={tweaks.heroVariant}
          options={[
            { value: 'auto', label: 'Auto (5s)' },
            { value: 'orbital', label: 'Orbital' },
            { value: 'network', label: 'Network' },
          ]}
          onChange={(v) => setTweak('heroVariant', v)}
        />
      </TweakSection>
      <TweakSection label="Brand">
        <TweakColor
          label="Accent color"
          value={ACCENTS[tweaks.accent].mint}
          options={[
            { value: '#85E6C6', label: 'Mint' },
            { value: '#7BD7F0', label: 'Cyan' },
            { value: '#9CB5D6', label: 'Steel' },
          ]}
          onChange={(v) => {
            const map = { '#85E6C6': 'mint', '#7BD7F0': 'cyan', '#9CB5D6': 'steel' };
            setTweak('accent', map[v] || 'mint');
          }}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

/* ================== APP ================== */
function HomeApp() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useApplyAccent(tweaks.accent);
  return (
    <I18nProvider>
      <Nav active="home"/>
      <Hero variant={tweaks.heroVariant}/>
      <HeroProofStrip/>
      <FusionModelSection/>
      <ServicesStrip/>
      <AISection/>
      <CasesSection/>
      <CTASection/>
      <Footer/>
      <CookieBanner/>
      <HomeTweaks tweaks={tweaks} setTweak={setTweak}/>
    </I18nProvider>
  );
}

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