/* ─── Main App ─── */
const TWEAKS = /*EDITMODE-BEGIN*/{
  "theme": "cream",
  "pageWidth": 60,
  "selectedPhoto": 4,
  "titleScale": 100,
  "bodyScale": 122,
  "photoScale": 78,
  "photoX": 0,
  "photoY": 0,
  "lang": "es",
  "mode": "light",
  "logoVersion": "tresTrazos"
}/*EDITMODE-END*/;

const PRESET_KEY = 'belmar_presets_v1';
const PRESET_SEED_KEY = 'belmar_presets_seeded_v2';
const LOGO_VERSION_KEY = 'belmar_logo_version_v1';
const TWEAK_KEYS = ['theme','pageWidth','titleScale','bodyScale','photoScale','photoX','photoY','selectedPhoto','lang','mode','logoVersion'];

function normalizeLogoVersion(value) {
  if (value === 'nocturno' || value === 'tresTrazos') return 'tresTrazos';
  if (value === 'clasico' || value === 'dosTrazos') return 'dosTrazos';
  return 'dosTrazos';
}

const BUNDLED_PRESETS = [
  { name: 'Config 1 — Pergamino Cálido',  savedAt: '2026-05-21T04:06:54.890Z',
    data: { theme:'cream', pageWidth:85,  titleScale:100, bodyScale:100, photoScale:100, photoX:0, photoY:0, lang:'es', mode:'light', selectedPhoto:0 } },
  { name: 'Config 2 — Marfil Editorial',  savedAt: '2026-05-21T04:06:54.890Z',
    data: { theme:'bone', pageWidth:80,  titleScale:110, bodyScale:96,  photoScale:90,  photoX:0, photoY:0, lang:'es', mode:'light', selectedPhoto:2 } },
  { name: 'Config 3 — Nocturno Premium',  savedAt: '2026-05-21T04:06:54.890Z',
    data: { theme:'cream', pageWidth:88,  titleScale:106, bodyScale:102, photoScale:95,  photoX:0, photoY:0, lang:'es', mode:'dark',  selectedPhoto:3 } },
];

// localStorage wrapper — incognito/private mode can throw SecurityError; fall back to memory
const _mem = {};
function lsGet(key) { try { return localStorage.getItem(key); } catch { return _mem[key] ?? null; } }
function lsSet(key, val) { try { localStorage.setItem(key, val); } catch { _mem[key] = val; } }

/* ─── Analytics: one helper fans out to GA4 + Meta + TikTok. No-ops when all inert. ───
   params._fb / params._tt override the Meta / TikTok event name; the rest are passed
   through as event params. Wrapped in try/catch so a pixel error never breaks a click. */
function track(name, params = {}) {
  const { _fb, _tt, ...rest } = params;
  try { if (window.gtag) window.gtag('event', name, rest); } catch {}
  try { if (window.fbq)  window.fbq('track', _fb || 'Lead', rest); } catch {}
  try { if (window.ttq)  window.ttq.track(_tt || 'Contact', rest); } catch {}
}

/* ─── Attribution: capture first-touch UTM + referrer once per session ───
   So a lead's origin survives navigation and rides along with the form submission. */
const ATTRIB_KEY = 'belmar_attribution_v1';
function captureAttribution() {
  try {
    if (sessionStorage.getItem(ATTRIB_KEY)) return; // first touch wins
    const p = new URLSearchParams(window.location.search);
    sessionStorage.setItem(ATTRIB_KEY, JSON.stringify({
      utm_source:   p.get('utm_source')   || '',
      utm_medium:   p.get('utm_medium')   || '',
      utm_campaign: p.get('utm_campaign') || '',
      utm_content:  p.get('utm_content')  || '',
      utm_term:     p.get('utm_term')     || '',
      referrer:     document.referrer     || '',
      landing_url:  window.location.href  || '',
    }));
  } catch {}
}
function getAttribution() {
  try { return JSON.parse(sessionStorage.getItem(ATTRIB_KEY) || '{}'); }
  catch { return {}; }
}

function loadPresets() {
  try {
    const stored = JSON.parse(lsGet(PRESET_KEY) || '[]');
    if (!lsGet(PRESET_SEED_KEY)) {
      const byName = new Map(BUNDLED_PRESETS.map(p => [p.name, p]));
      for (const p of stored) byName.set(p.name, p);
      const seeded = Array.from(byName.values());
      lsSet(PRESET_KEY, JSON.stringify(seeded));
      lsSet(PRESET_SEED_KEY, '1');
      return seeded;
    }
    return stored;
  } catch { return [...BUNDLED_PRESETS]; }
}
function savePresetList(list) {
  lsSet(PRESET_KEY, JSON.stringify(list));
}

const C = JSON.parse(document.getElementById('content-data').textContent);

// Build a wa.me link from the real number + a (localized) prefill message.
function waHref(message) {
  return `https://wa.me/${C.socials.whatsappE164}?text=${encodeURIComponent(message || '')}`;
}

const LANGS = [
  { code: 'es', label: 'ES' },
  { code: 'en', label: 'EN' },
  { code: 'de', label: 'DE' },
  { code: 'zh', label: '中文' },
];

/* ─── Utility bar (top right): language + theme toggle ─── */
function UtilityBar({ lang, setLang, mode, setMode, UI }) {
  return (
    <div className="util-bar">
      <div className="util-inner">
        <div className="lang-group">
          {LANGS.map((l, i) => (
            <React.Fragment key={l.code}>
              {i > 0 && <span className="lang-divider"></span>}
              <button
                className={`lang-btn ${lang === l.code ? 'active' : ''}`}
                onClick={() => setLang(l.code)}
                aria-label={l.code}
              >{l.label}</button>
            </React.Fragment>
          ))}
        </div>
        <div className="mode-toggle" role="group" aria-label="theme">
          <button
            className={`mode-opt ${mode === 'light' ? 'active' : ''}`}
            onClick={() => setMode('light')}
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
            {UI.light}
          </button>
          <button
            className={`mode-opt ${mode === 'dark' ? 'active' : ''}`}
            onClick={() => setMode('dark')}
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
            {UI.dark}
          </button>
        </div>
      </div>
    </div>
  );
}

function TranslationBanner({ notice }) {
  if (!notice) return null;
  return (
    <div className="translation-banner">
      <div className="inner">
        <strong>i</strong>{notice}
      </div>
    </div>
  );
}

function Nav({ activeId, themeColors, logoPalette, UI, logoVersion, onVersionChange }) {
  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({behavior:'smooth', block:'start'});
  };
  return (
    <nav className="nav-bar">
      <div className="nav-inner">
        <div onClick={() => scrollTo('top')}>
          <NavLogo palette={logoPalette} logoVersion={logoVersion}/>
        </div>
        <div className="nav-links">
          <button className={`nav-link ${activeId==='areas'?'active':''}`}      onClick={() => scrollTo('areas')}>{UI.nav_areas}</button>
          <button className={`nav-link ${activeId==='servicios'?'active':''}`}  onClick={() => scrollTo('servicios')}>{UI.nav_servicios}</button>
          <button className={`nav-link ${activeId==='socials'?'active':''}`}    onClick={() => scrollTo('socials')}>{UI.nav_socials}</button>
          <button className={`nav-link ${activeId==='contacto'?'active':''}`}   onClick={() => scrollTo('contacto')}>{UI.nav_contacto}</button>
        </div>
      </div>
    </nav>
  );
}

function Hero({ L, photoIndex, setPhotoIndex }) {
  const scrollTo = (id) => document.getElementById(id)?.scrollIntoView({behavior:'smooth'});
  return (
    <section className="hero">
      <div>
        <div className="hero-eyebrow">
          <span className="rule"></span>
          <span className="label-tiny">{L.hero.eyebrow}</span>
        </div>
        <h1 className="hero-title">{withEm(L.hero.title)}</h1>
        <p className="hero-sub">{L.hero.subtitle}</p>
        <div className="hero-actions">
          <button className="btn-primary" onClick={() => scrollTo('contacto')}>{L.hero.ctaPrimary}</button>
          <a className="btn-whatsapp" href={waHref(L.ui.wa_prefill)} target="_blank" rel="noopener noreferrer"
             onClick={() => track('whatsapp_click', { placement: 'hero', _fb: 'Contact', _tt: 'Contact' })}>
            {WA_ICON}<span>{L.ui.wa_label}</span>
          </a>
          <button className="btn-ghost"   onClick={() => scrollTo('areas')}>{L.hero.ctaSecondary}</button>
        </div>
      </div>
      <PhotoCarousel index={photoIndex} setIndex={setPhotoIndex} frozen={true}/>
    </section>
  );
}

function Intro({ L, UI }) {
  return (
    <section className="section">
      <div className="container">
        <div className="intro-body">
          <div className="section-eyebrow" style={{justifyContent:'center'}}>
            <span className="rule"></span>
            <span className="label-tiny">{UI.section_about}</span>
            <span className="rule"></span>
          </div>
          <h3>{withEm(L.intro.title)}</h3>
          <p>{L.intro.body}</p>
          <p>{L.intro.bodyExtra}</p>
          <div className="stats">
            {C.stats_nums.map((n, i) => (
              <div className="stat" key={i}>
                <div className="stat-num">{n}</div>
                <div className="stat-label">{L.stats_labels[i]}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Areas({ L, UI }) {
  return (
    <section className="section" id="areas">
      <div className="container">
        <div className="section-head">
          <div className="section-eyebrow">
            <span className="rule"></span>
            <span className="label-tiny">{UI.section_areas}</span>
            <span className="rule"></span>
          </div>
          <h2 className="section-title">{withEm(UI.areas_title)}</h2>
          <p className="section-sub">{UI.areas_sub}</p>
        </div>
        <div className="areas">
          {L.areas.map((a, i) => (
            <div className="area" key={C.area_ids[i]} id={`area-${C.area_ids[i]}`}>
              <div className="area-head">
                <span className="area-num">— {C.area_nums[i]}</span>
                <span className="area-name">{a.name}</span>
              </div>
              <p className="area-lead">{a.lead}</p>
              <p className="area-desc">{a.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Servicios({ L, UI }) {
  return (
    <section className="section alt" id="servicios">
      <div className="container">
        <div className="section-head">
          <div className="section-eyebrow">
            <span className="rule"></span>
            <span className="label-tiny">{UI.section_servicios}</span>
            <span className="rule"></span>
          </div>
          <h2 className="section-title">{L.serviciosEspeciales.title}</h2>
          <p className="section-sub">{L.serviciosEspeciales.intro}</p>
        </div>
        <div className="servicios-grid">
          {L.serviciosEspeciales.razones.map((r, i) => (
            <div className="razon-card" key={i}>
              <div className="razon-num">{i+1}.</div>
              <div className="razon-title">{r.title}</div>
              <div className="razon-desc">{r.desc}</div>
            </div>
          ))}
        </div>
        <div className="beneficios-strip">
          <h4>{withEm(UI.beneficios_title)}</h4>
          <p className="beneficios-sub">{UI.beneficios_sub}</p>
          <div className="beneficios-grid">
            {L.serviciosEspeciales.beneficios.map((b, i) => (
              <div className="beneficio" key={i}>
                <div className="beneficio-title">{b.title}</div>
                <div className="beneficio-desc">{b.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Planes({ L, UI }) {
  return (
    <section className="section" id="planes">
      <div className="container">
        <div className="section-head">
          <div className="section-eyebrow">
            <span className="rule"></span>
            <span className="label-tiny">{UI.section_planes}</span>
            <span className="rule"></span>
          </div>
          <h2 className="section-title">{withEm(UI.planes_title)}</h2>
          <p className="section-sub">{L.planesEmpresas.intro}</p>
        </div>
        <div className="planes-grid">
          {L.planesEmpresas.plans.map((p, i) => {
            const featured = i === C.plan_featured_index;
            return (
              <div className={`plan ${featured ? 'featured' : ''}`} key={i} data-featured-label={UI.plan_featured_label}>
                <div>
                  <div className="plan-name">{p.name}</div>
                  <div className="plan-sub">{p.subtitle}</div>
                </div>
                <div className="plan-price">{C.plan_prices[i]}</div>
                <ul className="plan-features">
                  {p.features.map((f, j) => <li key={j}>{f}</li>)}
                </ul>
                <button className="plan-cta" onClick={() => document.getElementById('contacto').scrollIntoView({behavior:'smooth'})}>{UI.plan_cta}</button>
              </div>
            );
          })}
        </div>
        <p style={{textAlign:'center',marginTop:32,fontFamily:'EB Garamond,serif',fontStyle:'italic',color:'var(--ink-soft)',fontSize:14}}>
          {L.planesEmpresas.note}
        </p>
      </div>
    </section>
  );
}

function Quote({ L }) {
  return (
    <section className="quote-section">
      <div className="container">
        <div className="quote-mark">"</div>
        <p className="quote-text">{L.quote.text}</p>
        <div className="quote-attr">— {L.quote.attr}</div>
      </div>
    </section>
  );
}

// TODO: Replace with real Formspree endpoint once Felipe's email is confirmed.
// Steps: formspree.io → Sign up → New Form → copy endpoint URL (https://formspree.io/f/XXXXXXXX)
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/PLACEHOLDER';

function Contacto({ L, UI, photoIndex }) {
  const photo = PHOTOS[photoIndex];
  const [formStatus, setFormStatus] = React.useState('idle'); // 'idle' | 'submitting' | 'success' | 'error'

  async function handleSubmit(e) {
    e.preventDefault();
    setFormStatus('submitting');
    const data = new FormData(e.target);
    // Stamp the lead with its first-touch origin so Felipe sees the source in the email.
    const attrib = getAttribution();
    Object.entries(attrib).forEach(([k, v]) => data.append(k, v || '(directo)'));
    data.append('_subject', 'Nuevo lead — belmaryañez.cl');
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        body: data,
        headers: { Accept: 'application/json' },
      });
      if (res.ok) {
        track('generate_lead', { method: 'form', _fb: 'Lead', _tt: 'SubmitForm' });
        setFormStatus('success');
        e.target.reset();
      } else {
        track('form_error', { reason: 'server' });
        setFormStatus('error');
      }
    } catch {
      track('form_error', { reason: 'network' });
      setFormStatus('error');
    }
  }

  return (
    <section className="section" id="contacto">
      <div className="container">
        <div className="section-head">
          <div className="section-eyebrow">
            <span className="rule"></span>
            <span className="label-tiny">{UI.section_contacto}</span>
            <span className="rule"></span>
          </div>
          <h2 className="section-title">{withEm(UI.contacto_title)}</h2>
        </div>
        <div className="contact-row">
          <div className="contact-left">
            <div className="contact-portrait">
              <img src={photo.src} alt={C.brand.founder}/>
            </div>
            <p className="contact-msg">{L.contact.intro}</p>
            <p className="contact-sign">{L.contact.signoff}</p>
            <div className="contact-direct">
              <a className="btn-whatsapp" href={waHref(UI.wa_prefill)} target="_blank" rel="noopener noreferrer"
                 onClick={() => track('whatsapp_click', { placement: 'contact', _fb: 'Contact', _tt: 'Contact' })}>
                {WA_ICON}<span>{UI.wa_label}</span>
              </a>
              <a className="contact-line" href={`tel:${C.region.phone.replace(/\s+/g, '')}`}
                 onClick={() => track('phone_click', { placement: 'contact', _fb: 'Contact', _tt: 'Contact' })}>
                {C.region.phone}
              </a>
              <a className="contact-line" href={`mailto:${C.region.email}?subject=${encodeURIComponent('Consulta desde belmaryañez.cl')}`}
                 onClick={() => track('email_click', { placement: 'contact', _fb: 'Contact', _tt: 'Contact' })}>
                {C.region.email}
              </a>
            </div>
          </div>
          <div className="contact-right">
            {formStatus === 'success' ? (
              <p className="form-feedback form-feedback--success">{L.contact.form_success}</p>
            ) : (
              <form onSubmit={handleSubmit}>
                <div className="form-row">
                  <label>{UI.form_name}</label>
                  <input type="text" name="name" required placeholder=""/>
                </div>
                <div className="form-row">
                  <label>{UI.form_email}</label>
                  <input type="email" name="email" required placeholder=""/>
                  <span className="hint">{UI.form_email_hint}</span>
                </div>
                <div className="form-row">
                  <label>{UI.form_message}</label>
                  <textarea name="message" required placeholder={UI.form_placeholder}></textarea>
                </div>
                {formStatus === 'error' && (
                  <p className="form-feedback form-feedback--error">{L.contact.form_error}</p>
                )}
                <button className="form-submit" type="submit" disabled={formStatus === 'submitting'}>
                  {formStatus === 'submitting' ? '…' : UI.form_submit}
                </button>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer({ UI }) {
  const socialLinks = C.socials.handle.links || {};
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-inner">
          <div className="footer-meta">© MMXXVI · {C.brand.name} · {UI.footer_rights}</div>
          <div className="footer-links">
            <a href={socialLinks.linkedin} target="_blank" rel="noopener noreferrer" onClick={() => track('social_click', { platform: 'linkedin', placement: 'footer' })}>LinkedIn</a>
            <a href={socialLinks.instagram} target="_blank" rel="noopener noreferrer" onClick={() => track('social_click', { platform: 'instagram', placement: 'footer' })}>Instagram</a>
            <a href={socialLinks.tiktok} target="_blank" rel="noopener noreferrer" onClick={() => track('social_click', { platform: 'tiktok', placement: 'footer' })}>TikTok</a>
            <a href="#top">{UI.section_about}</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ─── BY Monogram avatar (for handle proposals) ─── */
/* Faithful to assets/logo-by-handle-reference.png:
   cream square, big BY (B navy, Y gold), gold rule,
   "Belmar · Yáñez" in small caps, tiny "Cía." between rules. */
function BYAvatar({ size = 80, ink = '#1d2d44', gold = '#b8965a', bg = '#f4efe6' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100">
      <rect width="100" height="100" fill={bg}/>
      {/* BY letters — large, centered top */}
      <text x="36" y="50" fontFamily="Cormorant Garamond, serif" fontWeight="600"
            fontSize="38" fill={ink} textAnchor="middle" letterSpacing="-0.5">B</text>
      <text x="64" y="50" fontFamily="Cormorant Garamond, serif" fontWeight="300"
            fontSize="38" fill={gold} textAnchor="middle" letterSpacing="-0.5">Y</text>
      {/* Gold rule under BY */}
      <line x1="22" y1="60" x2="78" y2="60" stroke={gold} strokeWidth="0.9"/>
      {/* Name in small caps */}
      <text x="50" y="73" fontFamily="Cormorant SC, serif" fontWeight="500"
            fontSize="9" fill={ink} textAnchor="middle" letterSpacing="0.6">
        BELMAR · YÁÑEZ
      </text>
      {/* Cía. with side rules */}
      <line x1="32" y1="84" x2="42" y2="84" stroke={gold} strokeWidth="0.6"/>
      <text x="50" y="87" fontFamily="Cormorant Garamond, serif" fontStyle="italic"
            fontSize="8" fill={gold} textAnchor="middle" letterSpacing="0.4">Cía.</text>
      <line x1="58" y1="84" x2="68" y2="84" stroke={gold} strokeWidth="0.6"/>
    </svg>
  );
}

/* ─── Platform icons (small, inline) ─── */
const PLAT_ICONS = {
  tiktok: <svg viewBox="0 0 24 24"><path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64 2.93 2.93 0 0 1 .88.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5.8 20.1a6.34 6.34 0 0 0 10.86-4.43v-7a8.16 8.16 0 0 0 4.77 1.52v-3.4a4.85 4.85 0 0 1-1.84-.1z"/></svg>,
  instagram: <svg viewBox="0 0 24 24"><path d="M12 2.16c3.2 0 3.58.012 4.85.07 1.17.054 1.8.249 2.23.413.56.218.96.478 1.38.898.42.42.68.82.9 1.38.16.43.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s-.01 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38a3.72 3.72 0 0 1-1.38.9c-.43.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58-.01-4.85-.07c-1.17-.05-1.8-.25-2.23-.41a3.72 3.72 0 0 1-1.38-.9 3.72 3.72 0 0 1-.9-1.38c-.16-.43-.36-1.06-.41-2.23C2.17 15.58 2.16 15.2 2.16 12s.01-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.43-.16 1.06-.36 2.23-.41C8.42 2.17 8.8 2.16 12 2.16zM12 0C8.74 0 8.33.014 7.05.072 5.78.13 4.9.333 4.14.63a5.88 5.88 0 0 0-2.13 1.38A5.88 5.88 0 0 0 .63 4.14C.333 4.9.13 5.78.072 7.05.014 8.33 0 8.74 0 12s.014 3.67.072 4.95c.058 1.27.261 2.15.558 2.91a5.88 5.88 0 0 0 1.38 2.13c.66.66 1.34 1.06 2.13 1.38.76.297 1.64.5 2.91.558C8.33 23.986 8.74 24 12 24s3.67-.014 4.95-.072c1.27-.058 2.15-.261 2.91-.558a5.88 5.88 0 0 0 2.13-1.38 5.88 5.88 0 0 0 1.38-2.13c.297-.76.5-1.64.558-2.91C23.986 15.67 24 15.26 24 12s-.014-3.67-.072-4.95c-.058-1.27-.261-2.15-.558-2.91A5.88 5.88 0 0 0 21.99 2.01 5.88 5.88 0 0 0 19.86.63c-.76-.297-1.64-.5-2.91-.558C15.67.014 15.26 0 12 0zm0 5.84A6.16 6.16 0 1 0 12 18.16 6.16 6.16 0 0 0 12 5.84zm0 10.16A4 4 0 1 1 12 8a4 4 0 0 1 0 8zm6.41-11.85a1.44 1.44 0 1 0 0 2.88 1.44 1.44 0 0 0 0-2.88z"/></svg>,
  linkedin: <svg viewBox="0 0 24 24"><path d="M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.45v6.29zM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z"/></svg>,
  youtube: <svg viewBox="0 0 24 24"><path d="M23.5 6.2a3 3 0 0 0-2.1-2.1C19.5 3.6 12 3.6 12 3.6s-7.5 0-9.4.5A3 3 0 0 0 .5 6.2C0 8.1 0 12 0 12s0 3.9.5 5.8a3 3 0 0 0 2.1 2.1c1.9.5 9.4.5 9.4.5s7.5 0 9.4-.5a3 3 0 0 0 2.1-2.1c.5-1.9.5-5.8.5-5.8s0-3.9-.5-5.8zM9.6 15.6V8.4l6.2 3.6-6.2 3.6z"/></svg>,
};

const WA_ICON = <svg viewBox="0 0 24 24"><path d="M17.6 14.2c-.3-.15-1.77-.87-2.04-.97-.28-.1-.48-.15-.68.15-.2.3-.78.97-.96 1.17-.18.2-.36.22-.66.07-.3-.15-1.27-.47-2.42-1.5-.9-.8-1.5-1.78-1.67-2.08-.18-.3-.02-.46.13-.61.13-.13.3-.36.45-.54.15-.18.2-.3.3-.5.1-.2.05-.38-.02-.53-.08-.15-.68-1.62-.93-2.22-.24-.58-.5-.5-.68-.51l-.58-.01c-.2 0-.53.08-.8.38-.28.3-1.05 1.03-1.05 2.5 0 1.48 1.08 2.9 1.23 3.1.15.2 2.12 3.24 5.13 4.54.72.31 1.28.5 1.72.64.72.23 1.38.2 1.9.12.58-.09 1.77-.72 2.02-1.42.25-.7.25-1.3.18-1.42-.08-.13-.28-.2-.58-.35z M12 .04C5.4.04.05 5.4.05 12c0 2.12.55 4.18 1.6 6L0 24l6.2-1.62A11.94 11.94 0 0 0 12 23.96C18.6 23.96 23.95 18.6 23.95 12 23.95 5.4 18.6.04 12 .04zm0 21.84c-1.86 0-3.68-.5-5.26-1.45l-.38-.22-3.92 1.03 1.05-3.82-.25-.4A9.92 9.92 0 0 1 2.06 12c0-5.48 4.47-9.94 9.94-9.94 5.48 0 9.94 4.47 9.94 9.94 0 5.48-4.47 9.94-9.94 9.94z"/></svg>;

const DISPLAY_PLATFORMS = ['instagram', 'tiktok', 'linkedin'];

function Socials({ L, UI }) {
  const h = C.socials.handle;
  const platforms = h.platforms.filter(p => DISPLAY_PLATFORMS.includes(p) && h.links?.[p]);
  return (
    <section className="socials-section" id="socials">
      <div className="container">
        <div className="section-head">
          <div className="section-eyebrow">
            <span className="rule"></span>
            <span className="label-tiny">{UI.section_socials}</span>
            <span className="rule"></span>
          </div>
          <h2 className="section-title">{withEm(UI.socials_title)}</h2>
          <p className="section-sub">{UI.socials_sub}</p>
        </div>
        <div className="platform-grid">
          {platforms.map(plat => (
            <a
              className="platform-card"
              key={plat}
              href={h.links[plat]}
              target="_blank"
              rel="noopener noreferrer"
              aria-label={`${plat} · ${UI.socials_cta}`}
              title={UI.socials_cta}
              onClick={() => track('social_click', { platform: plat, placement: 'section' })}
            >
              <div className="platform-icon">{PLAT_ICONS[plat]}</div>
              <div className="platform-name">{plat}</div>
              <div className="platform-handle">{h.handle}</div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function WhatsAppFloat({ UI }) {
  return (
    <a className="wa-float" href={waHref(UI.wa_prefill)} target="_blank" rel="noopener noreferrer" aria-label={UI.wa_label}
       onClick={() => track('whatsapp_click', { placement: 'float', _fb: 'Contact', _tt: 'Contact' })}>
      <span className="wa-float-pulse"></span>
      {WA_ICON}
    </a>
  );
}

/* ─── Preset Manager ─── */
function PresetManager({ t, setTweak, photoIndex, setPhotoIndex }) {
  const [presets, setPresets] = React.useState(loadPresets);
  const [name, setName] = React.useState('');

  const handleSave = () => {
    const n = name.trim() || `Preset ${presets.length + 1}`;
    const data = { ...t, logoVersion: normalizeLogoVersion(t.logoVersion), selectedPhoto: photoIndex };
    const next = [...presets.filter(p => p.name !== n), { name: n, data, savedAt: new Date().toISOString() }];
    setPresets(next); savePresetList(next); setName('');
  };

  const handleApply = (p) => {
    const edits = {};
    for (const k of TWEAK_KEYS) {
      if (p.data[k] !== undefined && k !== 'selectedPhoto') {
        edits[k] = k === 'logoVersion' ? normalizeLogoVersion(p.data[k]) : p.data[k];
      }
    }
    setTweak(edits);
    if (p.data.selectedPhoto !== undefined) setPhotoIndex(p.data.selectedPhoto);
  };

  const handleDelete = (n) => {
    const next = presets.filter(p => p.name !== n);
    setPresets(next); savePresetList(next);
  };

  const handleExport = () => {
    const blob = new Blob([JSON.stringify(presets, null, 2)], {type:'application/json'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'belmar-presets.json'; a.click();
    URL.revokeObjectURL(url);
  };

  const fileInputRef = React.useRef(null);
  const handleImportClick = () => fileInputRef.current?.click();
  const handleImport = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    try {
      const text = await file.text();
      const imported = JSON.parse(text);
      if (!Array.isArray(imported)) throw new Error('Formato inválido');
      // Merge: imported overrides same-name presets
      const byName = new Map(presets.map(p => [p.name, p]));
      for (const p of imported) {
        if (p && p.name && p.data) byName.set(p.name, p);
      }
      const next = Array.from(byName.values());
      setPresets(next); savePresetList(next);
      alert(`Importados ${imported.length} preset(s).`);
    } catch (err) {
      alert('Error al importar: ' + err.message);
    }
    e.target.value = '';
  };

  const fmtDate = (iso) => {
    try { return new Date(iso).toLocaleDateString('es-CL', {day:'2-digit', month:'short', hour:'2-digit', minute:'2-digit'}); }
    catch { return ''; }
  };

  const inputStyle = {fontFamily:'Georgia,serif',fontSize:13,padding:'6px 8px',border:'1px solid #ddd',borderRadius:3,flex:1,outline:'none',background:'#fff',color:'#222'};
  const btnStyle = {fontFamily:'Cormorant SC,serif',fontSize:10,letterSpacing:'0.15em',padding:'6px 10px',background:'#1d2d44',color:'#fff',border:'none',borderRadius:3,cursor:'pointer',textTransform:'uppercase'};
  const subBtnStyle = {fontFamily:'Cormorant SC,serif',fontSize:9,letterSpacing:'0.12em',padding:'4px 8px',background:'transparent',color:'#1d2d44',border:'1px solid #ccc',borderRadius:3,cursor:'pointer',textTransform:'uppercase'};

  return (
    <div style={{display:'flex',flexDirection:'column',gap:10,fontFamily:'Georgia,serif'}}>
      <div style={{display:'flex',gap:6}}>
        <input style={inputStyle} placeholder="Nombre del preset" value={name} onChange={e=>setName(e.target.value)} onKeyDown={e=>e.key==='Enter' && handleSave()}/>
        <button style={btnStyle} onClick={handleSave}>Guardar</button>
      </div>
      {presets.length === 0 ? (
        <div style={{fontSize:12,color:'#888',fontStyle:'italic'}}>Sin presets guardados.</div>
      ) : (
        <div style={{display:'flex',flexDirection:'column',gap:6,maxHeight:280,overflow:'auto'}}>
          {presets.map(p => (
            <div key={p.name} style={{display:'flex',flexDirection:'column',gap:4,padding:'8px 10px',background:'rgba(0,0,0,0.04)',borderRadius:4}}>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:8}}>
                <strong style={{fontSize:13,color:'#1d2d44'}}>{p.name}</strong>
                <span style={{fontSize:11,color:'#999',fontStyle:'italic'}}>{fmtDate(p.savedAt)}</span>
              </div>
              <div style={{fontSize:11,color:'#666'}}>
                {p.data.theme} · {p.data.lang || 'es'} · pw {p.data.pageWidth}% · t {p.data.titleScale}% · b {p.data.bodyScale}% · f {p.data.photoScale}%
              </div>
              <div style={{display:'flex',gap:6,marginTop:2}}>
                <button style={subBtnStyle} onClick={()=>handleApply(p)}>Aplicar</button>
                <button style={{...subBtnStyle,color:'#a64'}} onClick={()=>handleDelete(p.name)}>Eliminar</button>
              </div>
            </div>
          ))}
          <div style={{display:'flex',gap:6,marginTop:4}}>
            <button style={{...subBtnStyle,flex:1}} onClick={handleExport}>Exportar JSON</button>
            <button style={{...subBtnStyle,flex:1}} onClick={handleImportClick}>Importar JSON</button>
          </div>
        </div>
      )}
      {presets.length === 0 && (
        <button style={subBtnStyle} onClick={handleImportClick}>Importar JSON</button>
      )}
      <input ref={fileInputRef} type="file" accept="application/json,.json" onChange={handleImport} style={{display:'none'}}/>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks({
    ...TWEAKS,
    logoVersion: normalizeLogoVersion(lsGet(LOGO_VERSION_KEY) || TWEAKS.logoVersion),
  });
  const [photoIndex, setPhotoIndex] = React.useState(t.selectedPhoto || 0);
  const [activeId, setActiveId] = React.useState(null);
  const logoVersion = normalizeLogoVersion(t.logoVersion);

  React.useEffect(() => { captureAttribution(); }, []);
  React.useEffect(() => { setTweak('selectedPhoto', photoIndex); }, [photoIndex]);
  React.useEffect(() => {
    if (t.logoVersion !== logoVersion) {
      setTweak('logoVersion', logoVersion);
    }
  }, [t.logoVersion, logoVersion]);
  React.useEffect(() => { lsSet(LOGO_VERSION_KEY, logoVersion); }, [logoVersion]);

  React.useEffect(() => {
    const ids = ['areas','servicios','socials','contacto'];
    const handle = () => {
      let current = null;
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        const r = el.getBoundingClientRect();
        if (r.top <= 120 && r.bottom > 120) { current = id; break; }
      }
      setActiveId(current);
    };
    window.addEventListener('scroll', handle, {passive:true});
    handle();
    return () => window.removeEventListener('scroll', handle);
  }, []);

  // Resolve current lang
  const lang = t.lang || 'es';
  const L  = C.langs[lang] || C.langs.es;
  const UI = L.ui;

  // Resolve theme: mode toggle switches between cream (light) and dark
  const effectiveTheme = t.mode === 'dark' ? 'dark' : (t.theme === 'dark' ? 'cream' : t.theme);

  const themeColors = effectiveTheme === 'dark'
    ? { gold: '#c9a972', navInk: '#f0ebe1' }
    : effectiveTheme === 'bone'
      ? { gold: '#a8854b', navInk: '#f0ebe1' }
      : { gold: '#b8965a', navInk: '#f0ebe1' };
  const logoPalette = effectiveTheme === 'dark'
    ? { primary: '#5a87bf', secondary: '#c9a972', tertiary: '#9bbfe3' }
    : effectiveTheme === 'bone'
      ? { primary: '#f0ebe1', secondary: '#a8854b', tertiary: '#d8c4a3' }
      : { primary: '#f0ebe1', secondary: '#b8965a', tertiary: '#dbc59f' };

  // Update document language
  React.useEffect(() => {
    document.documentElement.lang = lang === 'zh' ? 'zh-CN' : lang;
  }, [lang]);

  return (
    <>
      <div className={`page theme-${effectiveTheme}`} id="top" style={{'--page-width': `${t.pageWidth}%`, '--title-scale': t.titleScale/100, '--body-scale': t.bodyScale/100, '--photo-scale': t.photoScale/100, '--photo-x': `${t.photoX}px`, '--photo-y': `${t.photoY}px`}}>
        <UtilityBar
          lang={lang}
          setLang={v => setTweak('lang', v)}
          mode={t.mode || 'light'}
          setMode={v => setTweak('mode', v)}
          UI={UI}
        />
        <Nav activeId={activeId} themeColors={themeColors} logoPalette={logoPalette} UI={UI}
          logoVersion={logoVersion}
          onVersionChange={v => setTweak('logoVersion', normalizeLogoVersion(v))}
        />
        <TranslationBanner notice={UI.translation_notice}/>
        <div className="container">
          <Hero L={L} photoIndex={photoIndex} setPhotoIndex={setPhotoIndex}/>
        </div>
        <Intro L={L} UI={UI}/>
        <Areas L={L} UI={UI}/>
        <Servicios L={L} UI={UI}/>
        <Socials L={L} UI={UI}/>
        <Quote L={L}/>
        <Contacto L={L} UI={UI} photoIndex={photoIndex}/>
        <Footer UI={UI}/>
      </div>

      <TweaksPanel>
        <TweakSection label="Paleta avanzada">
          <TweakRadio
            label="Paleta light"
            value={t.theme === 'dark' ? 'cream' : t.theme}
            onChange={v => setTweak('theme', v)}
            options={[
              {value:'cream', label:'Pergamino'},
              {value:'bone',  label:'Marfil'},
            ]}
          />
          <div style={{fontSize:11,color:'#888',fontStyle:'italic',marginTop:6,fontFamily:'Georgia,serif'}}>
            El botón día/noche del nav usa esta paleta como modo claro.
          </div>
        </TweakSection>
        <TweakSection label="Layout">
          <TweakSlider label="Ancho de página" value={t.pageWidth} onChange={v => setTweak('pageWidth', v)} min={60} max={100} step={1} unit="%"/>
        </TweakSection>
        <TweakSection label="Tipografía">
          <TweakSlider label="Tamaño de títulos" value={t.titleScale} onChange={v => setTweak('titleScale', v)} min={70} max={140} step={2} unit="%"/>
          <TweakSlider label="Tamaño del texto" value={t.bodyScale} onChange={v => setTweak('bodyScale', v)} min={80} max={130} step={2} unit="%"/>
        </TweakSection>
        <TweakSection label="Foto del Hero">
          <TweakSlider label="Tamaño" value={t.photoScale} onChange={v => setTweak('photoScale', v)} min={50} max={110} step={2} unit="%"/>
          <TweakSlider label="Posición horizontal" value={t.photoX} onChange={v => setTweak('photoX', v)} min={-200} max={200} step={2} unit="px"/>
          <TweakSlider label="Posición vertical" value={t.photoY} onChange={v => setTweak('photoY', v)} min={-200} max={200} step={2} unit="px"/>
          <div style={{display:'flex',flexDirection:'column',gap:8,fontFamily:'Georgia,serif',fontSize:13,marginTop:8}}>
            <div>Actual: <strong>{String(photoIndex+1).padStart(2,'0')}</strong> · {PHOTOS[photoIndex].label}</div>
            <div style={{color:'#888',fontStyle:'italic',fontSize:12}}>
              Carrusel desactivado — foto fija.
            </div>
          </div>
        </TweakSection>
        <TweakSection label="Presets">
          <PresetManager t={t} setTweak={setTweak} photoIndex={photoIndex} setPhotoIndex={setPhotoIndex}/>
        </TweakSection>
      </TweaksPanel>
      <WhatsAppFloat UI={UI}/>
    </>
  );
}

window.addEventListener('keydown', (e) => {
  if (['INPUT','TEXTAREA'].includes(document.activeElement?.tagName)) return;
  if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
    const btn = document.querySelector(`.photo-nav.${e.key === 'ArrowLeft' ? 'prev' : 'next'}`);
    if (btn) btn.click();
  }
});

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