/* 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 <= 1 ? 'Los espacios se están llenando. Una vez rentado, el nivel queda cerrado.'
                  : floor.av <= 2 ? 'Los espacios se están llenando. Agenda la visita esta semana.'
                  : 'Buena disponibilidad. Elige el espacio que mejor se adapte a tu empresa.'}
              </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 OfficeHierarchy({ floor }) {
  const eco = ZONES[floor.zone]?.eco || 'corporativo';
  const types = TYPE_META[eco] || {};

  // Retail = single planta libre
  if (eco === 'retail') {
    const o = floor.offices[0];
    const meta = types['Planta libre'];
    return (
      <div className="office-hierarchy retail">
        <AnchorCard office={o} meta={meta} floor={floor} />
      </div>
    );
  }

  // Group by type letter
  const groupByType = (letter) => floor.offices.filter(o => typeKey(o) === letter);
  const anchors = groupByType('C');
  const mids    = groupByType('B');
  const boutiqs = groupByType('A');

  return (
    <div className="office-hierarchy">
      {/* TIER 01 · ANCLA — gold prominence */}
      {anchors.length > 0 && (
        <section className="office-tier office-tier-anchor">
          <header className="tier-head">
            <span className="tier-no">01</span>
            <div className="tier-meta">
              <span className="tier-label">Ancla · Tipo C · {types.C?.m2}</span>
              <span className="tier-cap">{types.C?.capacity}</span>
            </div>
            <p className="tier-tagline">{types.C?.tagline}</p>
          </header>
          {anchors.map(o => <AnchorCard key={o.code} office={o} meta={types.C} floor={floor} />)}
        </section>
      )}

      {/* TIER 02 · CONSOLIDACIÓN */}
      {mids.length > 0 && (
        <section className="office-tier office-tier-mid">
          <header className="tier-head">
            <span className="tier-no">02</span>
            <div className="tier-meta">
              <span className="tier-label">Consolidación · Tipo B · {types.B?.m2}</span>
              <span className="tier-cap">{types.B?.capacity}</span>
            </div>
            <p className="tier-tagline">{types.B?.tagline}</p>
          </header>
          {mids.map(o => <MidCard key={o.code} office={o} meta={types.B} floor={floor} />)}
        </section>
      )}

      {/* TIER 03 · BOUTIQUE */}
      {boutiqs.length > 0 && (
        <section className="office-tier office-tier-boutique">
          <header className="tier-head">
            <span className="tier-no">03</span>
            <div className="tier-meta">
              <span className="tier-label">Boutique · Tipo A · {types.A?.m2}</span>
              <span className="tier-cap">{types.A?.capacity}</span>
            </div>
            <p className="tier-tagline">{types.A?.tagline}</p>
          </header>
          <div className="boutique-grid">
            {boutiqs.map(o => <BoutiqueCard key={o.code} office={o} meta={types.A} floor={floor} />)}
          </div>
        </section>
      )}
    </div>
  );
}

function AnchorCard({ office, meta, floor }) {
  const isAvail = office.ok;
  return (
    <article className={`anchor-card ${isAvail ? 'av' : 'ren'}`}>
      <div className="anchor-card-num">
        <span className="ac-letter">{meta?.letter}</span>
        <span className="ac-m2">{office.m2} m²</span>
      </div>
      <div className="anchor-card-body">
        <div className="anchor-code-row">
          <span className="anchor-code">{office.code}</span>
          {isAvail
            ? <span className="anchor-pill av">Disponible</span>
            : <span className="anchor-pill ren">Rentado</span>}
        </div>
        <h3 className="anchor-title">{meta?.tagline}</h3>
        {meta?.anchorCopy && (
          <p className="anchor-strategy">{meta.anchorCopy}</p>
        )}
        <div className="anchor-spec-grid">
          <div>
            <div className="spec-lbl">Ideal para</div>
            <ul className="spec-list">
              {(meta?.idealFor || []).map((it, i) => <li key={i}>{it}</li>)}
            </ul>
          </div>
          <div>
            <div className="spec-lbl">Capacidad</div>
            <div className="spec-val">{meta?.capacity}</div>
            <div className="spec-lbl" style={{ marginTop:18 }}>Entrega</div>
            <div className="spec-val">Obra gris</div>
          </div>
        </div>
        <div className="anchor-foot">
          <div className="anchor-price">
            {FMT(office.price)}<small>/mes</small>
          </div>
          {isAvail ? (
            <button className="btn btn-gold" onClick={() => openChat(floor.id)}>
              Agendar visita <Icon n="ti-arrow-right" />
            </button>
          ) : (
            <span className="anchor-rented">
              <Icon n="ti-lock" /> Rentado · sin disponibilidad
            </span>
          )}
        </div>
      </div>
    </article>
  );
}

function MidCard({ office, meta, floor }) {
  const isAvail = office.ok;
  return (
    <article className={`mid-card ${isAvail ? 'av' : 'ren'}`} onClick={() => isAvail && openChat(floor.id)}>
      <div className="mid-card-left">
        <div className="mid-letter">{meta?.letter}</div>
        <div className="mid-code">{office.code}</div>
        <div className="mid-m2">{office.m2} m²</div>
      </div>
      <div className="mid-card-mid">
        <div className="mid-tagline">{meta?.tagline}</div>
        <div className="mid-ideal">
          <span className="mid-ideal-lbl">Ideal para</span>
          <span>{(meta?.idealFor || []).join(' · ')}</span>
        </div>
        <div className="mid-cap">{meta?.capacity}</div>
      </div>
      <div className="mid-card-right">
        <div className="mid-price">{FMT(office.price)}<small>/mes</small></div>
        {isAvail
          ? <span className="mid-pill av">Disponible <span aria-hidden="true">→</span></span>
          : <span className="mid-pill ren"><Icon n="ti-lock" /> Rentado</span>}
      </div>
    </article>
  );
}

function BoutiqueCard({ office, meta, floor }) {
  const isAvail = office.ok;
  return (
    <article className={`boutique-card ${isAvail ? 'av' : 'ren'}`} onClick={() => isAvail && openChat(floor.id)}>
      <div className="boutique-head">
        <span className="boutique-letter">{meta?.letter}</span>
        <span className="boutique-code">{office.code}</span>
      </div>
      <div className="boutique-m2">{office.m2} m²</div>
      <div className="boutique-tagline">{meta?.tagline}</div>
      <div className="boutique-foot">
        <div className="boutique-price">{FMT(office.price)}<small>/mes</small></div>
        {isAvail
          ? <span className="boutique-pill av">Disponible <span aria-hidden="true">→</span></span>
          : <span className="boutique-pill ren"><Icon n="ti-lock" /></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 TABLE */}
      <section className="section tight cream">
        <div className="container">
          <div className="section-head" style={{ marginBottom:48 }}>
            <div className="kicker">02 / Los tres tamaños</div>
            <h2 style={{ fontSize:'clamp(32px,4vw,48px)' }}>Una lógica <em>de ancla.</em></h2>
            <p>Cada nivel se compone de tres tamaños. El espacio ancla (137 m²) define la imagen del nivel y atrae el flujo principal. Los de consolidación (120 m²) acompañan. Los boutique (85 m²) se benefician del clúster que el ancla construye.</p>
          </div>
          <OfficeHierarchy 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>
      )}

      {/* 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">04 / 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 });
