/* Torre Auro — Level page (editorial) */

function AvailabilityStrip({ floor }) {
  const z = ZONES[floor.zone];
  const rentedCount = floor.tot - floor.av;
  const urgent = floor.av === 1;

  return (
    <div style={{ background: z.bgHex, borderTop:`1px solid ${z.accHex}22`, borderBottom:`1px solid ${z.accHex}22` }}>
      <div className="container">
        <div className="av-strip">
          <div className="av-strip-inner">
            <div className="av-strip-dots" aria-label="Disponibilidad">
              {Array.from({ length: floor.tot }).map((_, j) => {
                const rented = j < rentedCount;
                const cls = `av-strip-dot ${!rented && urgent ? 'urgent' : ''}`;
                return (
                  <div
                    key={j}
                    className={cls}
                    style={{ background: rented ? 'rgba(12,27,51,.15)' : z.accHex }}
                  />
                );
              })}
            </div>
            <div className="av-strip-text">
              <div className="av-strip-title" style={{ color: z.accHex, fontFamily:'var(--serif)', fontSize:26, fontWeight:500, lineHeight:1.2 }}>
                {floor.av === 0
                  ? 'Nivel completamente ocupado.'
                  : floor.av === 1
                    ? <>Solo <em style={{fontStyle:'italic'}}>un espacio</em> disponible de {floor.tot}.</>
                    : <>{floor.av} de {floor.tot} <em style={{fontStyle:'italic'}}>disponibles</em>.</>}
              </div>
              <div className="av-strip-text sub" style={{fontSize:14, color:'var(--ink-2)', marginTop:6, fontWeight:400}}>
                {floor.av === 0 ? 'Este nivel ya completó su ecosistema de inquilinos.'
                  : floor.av === 1 ? 'Queda un espacio para completar el ecosistema de este nivel.'
                  : 'Elige el espacio que mejor se integre a tu operación.'}
              </div>
            </div>
            <button className="btn btn-navy btn-sm" onClick={() => openChat(floor.id)}>
              Agendar visita <Icon n="ti-arrow-right" />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function OfficeDirectory({ floor }) {
  const eco = ZONES[floor.zone]?.eco || 'corporativo';
  const types = TYPE_META[eco] || {};
  const z = ZONES[floor.zone];

  if (eco === 'retail') {
    const o = floor.offices[0];
    return (
      <div className="off-dir">
        <OfficeCardCompact office={o} meta={types['Planta libre']} floor={floor} tier="ancla" />
      </div>
    );
  }

  const groupByType = (letter) => floor.offices.filter(o => typeKey(o) === letter);
  const tiers = [
    { key:'C', label:'Ancla', sub:'137 m²', cls:'ancla',  list:groupByType('C') },
    { key:'B', label:'Consolidación', sub:'120 m²', cls:'mid', list:groupByType('B') },
    { key:'A', label:'Boutique', sub:'85 m²', cls:'boutique', list:groupByType('A') },
  ];

  return (
    <div className="off-dir">
      {tiers.map(t => t.list.length > 0 && (
        <div key={t.key} className="off-dir-group">
          <div className="off-dir-grouphead">
            <span className="off-dir-grouplabel" style={{ color: z.accHex }}>{t.label}</span>
            <span className="off-dir-groupsub">Tipo {t.key} · {t.sub} · {t.list.filter(o=>o.ok).length} disp.</span>
          </div>
          <div className={`off-dir-grid ${t.cls === 'boutique' ? 'cols' : ''}`}>
            {t.list.map(o => (
              <OfficeCardCompact key={o.code} office={o} meta={types[t.key]} floor={floor} tier={t.cls} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function OfficeCardCompact({ office, meta, floor, tier }) {
  const z = ZONES[floor.zone];
  const isAvail = office.ok;
  const isAnchor = tier === 'ancla';
  return (
    <article
      className={`offc ${tier} ${isAvail ? 'av' : 'ren'}`}
      onClick={() => navigate(`/${floor.id}/${office.code}`)}
      role="button"
      tabIndex={0}
      style={isAnchor && isAvail ? { borderTopColor: z.accHex } : {}}
    >
      <div className="offc-top">
        <span className="offc-letter" style={{ color: z.accHex }}>{meta?.letter}</span>
        <span className={`offc-status ${isAvail ? 'av' : 'ren'}`}>
          {isAvail ? 'Disponible' : 'Rentado'}
        </span>
      </div>
      <div className="offc-code">{office.code}</div>
      <div className="offc-meta">{office.m2} m² · {office.type}</div>
      {isAnchor && <p className="offc-tagline">{meta?.tagline}</p>}
      <div className="offc-foot">
        <span className="offc-price">{FMT(office.price)}<small>/mes</small></span>
        <span className="offc-go" style={{ color: z.accHex }}>
          Ver oficina <span aria-hidden="true">→</span>
        </span>
      </div>
    </article>
  );
}

function Faq({ items }) {
  const [open, setOpen] = useState(new Set([0]));
  const refs = useRef({});

  function toggle(i) {
    setOpen(prev => {
      const next = new Set(prev);
      if (next.has(i)) next.delete(i); else next.add(i);
      return next;
    });
  }

  return (
    <div className="faq-list">
      {items.map((f, i) => {
        const isOp = open.has(i);
        const h = refs.current[i]?.scrollHeight || 0;
        return (
          <div key={i} className={`faq-item ${isOp ? 'op' : ''}`}>
            <button className="faq-q" onClick={() => toggle(i)} aria-expanded={isOp}>
              <span className="faq-no">{pad2(i + 1)}</span>
              <span>{f.q}</span>
              <Icon n="ti-chevron-down" className="faq-chev" />
            </button>
            <div
              className="faq-a"
              style={{ maxHeight: isOp ? h : 0 }}
              ref={el => { refs.current[i] = el; }}
            >
              <div className="faq-a-inner">{f.a}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function LevelPage({ floor }) {
  const z = ZONES[floor.zone];

  return (
    <div className="lvl-page">
      {/* HERO */}
      <section className="lvl-hero">
        <div className={`bg-cover zoom ${floor.bgClass}`} aria-hidden="true" />
        <div
          className="lvl-hero-overlay"
          style={{
            background:`linear-gradient(180deg, rgba(12,27,51,.45) 0%, rgba(12,27,51,.95) 100%), linear-gradient(120deg, ${z.accHex}26 0%, transparent 60%)`
          }}
        />
        <div className="container">
          <button className="lvl-back" onClick={() => navigate('/')}>
            <Icon n="ti-arrow-left" /> Volver al directorio
          </button>

          <div className="lvl-hero-grid">
            <div className="lvl-hero-num">{floor.sh}</div>
            <div>
              <div className="lvl-tag" style={{ color: z.accHex, borderColor: z.accHex }}>
                <span style={{width:6,height:6,background:z.accHex,borderRadius:'50%'}} />
                {floor.eyebrow}
              </div>
              <h1>{floor.name}</h1>
              <p className="desc">{floor.desc}</p>
              <div className="price-pill">
                <span className="from">Desde</span>
                <span className="range">
                  {floor.pMin === floor.pMax ? FMT(floor.pMin) : `${FMT(floor.pMin)} – ${FMT(floor.pMax)}`}
                </span>
                <span className="unit">/ mes · obra gris</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* AVAILABILITY */}
      <AvailabilityStrip floor={floor} />

      {/* INFO */}
      <section className="section tight">
        <div className="container">
          <div className="section-head" style={{ marginBottom:48 }}>
            <div className="kicker">01 / La propuesta del nivel</div>
            <h2 style={{ fontSize:'clamp(32px,4vw,48px)' }}>Por qué <em>este nivel</em>, y para <em>quién</em>.</h2>
          </div>

          <div className="info-grid">
            <div className="info-block">
              <div className="block-no">01 · Argumentos</div>
              <h3>Por qué <em>este nivel</em></h3>
              {floor.bens.map((b, i) => (
                <div key={i} className="ben-row">
                  <span className="no">/ {pad2(i + 1)}</span>
                  <span>{b}</span>
                </div>
              ))}
            </div>
            <div className="info-block">
              <div className="block-no">02 · Buyer persona</div>
              <h3>Perfecto para</h3>
              {floor.personas.map((p, i) => (
                <div key={i} className="persona-row">
                  <span className="persona-no">{pad2(i + 1)}</span>
                  <div className="persona-text">
                    <div className="name">{p.name}</div>
                    <div className="desc">{p.desc}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* OFFICE DIRECTORY */}
      <section className="section tight cream">
        <div className="container">
          <div className="section-head" style={{ marginBottom:40 }}>
            <div className="kicker">02 / Los espacios</div>
            <h2 style={{ fontSize:'clamp(32px,4vw,48px)' }}>Elige tu <em>oficina.</em></h2>
            <p>Tres tamaños por nivel. Toca una oficina para ver su detalle, plano y disponibilidad.</p>
          </div>
          <OfficeDirectory floor={floor} />
        </div>
      </section>

      {/* THE PLAN */}
      {floor.planClass && (
        <section className="section tight">
          <div className="container">
            <div className="section-head" style={{ marginBottom:48 }}>
              <div className="kicker">03 / El plano</div>
              <h2 style={{ fontSize:'clamp(32px,4vw,48px)' }}>La <em>distribución</em> del nivel.</h2>
              <p>Plano arquitectónico del nivel {floor.sh}. La franja de color en la elevación lateral indica la posición del nivel en el edificio. En la planta se identifican las oficinas A (boutique), B (consolidación) y C (ancla).</p>
            </div>

            <figure className="plan-figure">
              <div className="plan-frame">
                <div className={`plan-img ${floor.planClass}`} role="img" aria-label={`Plano del nivel ${floor.sh}`} />
              </div>
              <figcaption className="plan-caption">
                <div className="plan-cap-cell">
                  <span className="plan-cap-lbl">Sección</span>
                  <span className="plan-cap-val">{floor.sh}</span>
                </div>
                <div className="plan-cap-cell">
                  <span className="plan-cap-lbl">Ancla · C</span>
                  <span className="plan-cap-val">137.45 m²</span>
                </div>
                <div className="plan-cap-cell">
                  <span className="plan-cap-lbl">Consolidación · B</span>
                  <span className="plan-cap-val">120.00 m²</span>
                </div>
                <div className="plan-cap-cell">
                  <span className="plan-cap-lbl">Boutique · A</span>
                  <span className="plan-cap-val">3 × 85.00 m²</span>
                </div>
                <div className="plan-cap-cell">
                  <span className="plan-cap-lbl">Orientación</span>
                  <span className="plan-cap-val">Av. Tiburón · Ruiz Cortines</span>
                </div>
              </figcaption>
            </figure>
          </div>
        </section>
      )}

      {/* NICHE COMPETITION MAP */}
      <NicheMap floor={floor} />

      {/* FAQ */}
      <section className="section tight">
        <div className="container">
          <div className="section-head" style={{ textAlign:'center', margin:'0 auto 64px', maxWidth:680 }}>
            <div className="kicker center">05 / Preguntas frecuentes</div>
            <h2 style={{ fontSize:'clamp(32px,4vw,48px)' }}>Dudas <em>sobre este nivel</em>.</h2>
          </div>
          <Faq items={floor.faqs} />
        </div>
      </section>

      {/* CTA */}
      <CtaBanner
        no={pad2(floor.num + 4)}
        eyebrow={floor.cta.ey}
        title={floor.cta.h}
        sub={floor.cta.s}
        primary="Hablar con un asesor"
        secondary="Solicitar planos"
        onPrimary={() => openChat(floor.id)}
        onSecondary={() => openChat(floor.id + '-planos')}
      />

      {/* NEXT LEVEL */}
      <section className="section tight cream">
        <div className="container">
          <div className="section-head" style={{ marginBottom:32, maxWidth:'100%' }}>
            <div className="kicker">04 / Continuar el recorrido</div>
          </div>
          <div className="next-card" onClick={() => navigate('/' + floor.next.id)}>
            <div className="num">{FLOOR_BY_ID[floor.next.id]?.sh}</div>
            <div>
              <div className="lbl">{floor.next.sub}</div>
              <div className="name">
                {floor.next.label.split('—')[0]}<em>— {floor.next.label.split('—')[1]?.trim()}</em>
              </div>
              <div className="sub">
                {FLOOR_BY_ID[floor.next.id]?.av ?? 0}/{FLOOR_BY_ID[floor.next.id]?.tot ?? 0} disponibles · desde {FMT(FLOOR_BY_ID[floor.next.id]?.pMin ?? 0)}/mes
              </div>
            </div>
            <div className="arrow"><Icon n="ti-arrow-right" /></div>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { LevelPage });
