// Tech, Plans, Gallery, Progress

const Tech = ({ lang }) => {
  const d = window.SITE_DATA.tech[lang];
  return (
    <section className="section" id="tech">
      <div className="container">
        <div className="section-head reveal">
          <div className="kicker">{d.kicker}</div>
          <h2>{d.title}</h2>
        </div>
        <div className="tech-layout reveal">
          <div className="tech-media">
            <img src="assets/tech-facade.png" alt="Фасад QASIET CITY" />
          </div>
          <div className="tech-text">
            <p className="tech-intro">{d.intro}</p>
            <div className="tech-groups">
              {d.groups.map((g, i) =>
              <div key={i} className="tech-group">
                  <h3>{g.t}</h3>
                  <ul>
                    {g.lines.map((l, j) =>
                  <li key={j}>{l}</li>
                  )}
                  </ul>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>);

};

// Generated apartment plan SVG
const PlanSVG = ({ rooms }) => {
  // Different schematic layouts based on room count
  const stroke = "#3D3933";
  const fill = "rgba(225,183,120,0.10)";
  const wallW = 1.5;
  if (rooms === 1) {
    return (
      <svg viewBox="0 0 200 150" preserveAspectRatio="xMidYMid meet">
        <rect x="10" y="20" width="180" height="110" fill={fill} stroke={stroke} strokeWidth={wallW} />
        <line x1="100" y1="20" x2="100" y2="130" stroke={stroke} strokeWidth={wallW} />
        <line x1="100" y1="80" x2="190" y2="80" stroke={stroke} strokeWidth={wallW} />
        <line x1="60" y1="20" x2="60" y2="50" stroke={stroke} strokeWidth={wallW} />
        <line x1="10" y1="50" x2="60" y2="50" stroke={stroke} strokeWidth={wallW} />
        <text x="35" y="40" fontSize="6" fill="#4A5552" fontFamily="monospace">SAN</text>
        <text x="20" y="95" fontSize="7" fill="#4A5552" fontFamily="monospace">LIVING</text>
        <text x="135" y="55" fontSize="7" fill="#4A5552" fontFamily="monospace">BED</text>
        <text x="135" y="110" fontSize="7" fill="#4A5552" fontFamily="monospace">KIT</text>
      </svg>);

  }
  if (rooms === 2) {
    return (
      <svg viewBox="0 0 200 150" preserveAspectRatio="xMidYMid meet">
        <rect x="10" y="20" width="180" height="110" fill={fill} stroke={stroke} strokeWidth={wallW} />
        <line x1="80" y1="20" x2="80" y2="130" stroke={stroke} strokeWidth={wallW} />
        <line x1="140" y1="20" x2="140" y2="80" stroke={stroke} strokeWidth={wallW} />
        <line x1="80" y1="80" x2="190" y2="80" stroke={stroke} strokeWidth={wallW} />
        <line x1="40" y1="80" x2="80" y2="80" stroke={stroke} strokeWidth={wallW} />
        <line x1="40" y1="50" x2="80" y2="50" stroke={stroke} strokeWidth={wallW} />
        <text x="20" y="40" fontSize="6" fill="#4A5552" fontFamily="monospace">HALL</text>
        <text x="20" y="68" fontSize="6" fill="#4A5552" fontFamily="monospace">SAN</text>
        <text x="20" y="110" fontSize="6" fill="#4A5552" fontFamily="monospace">KIT</text>
        <text x="100" y="55" fontSize="6" fill="#4A5552" fontFamily="monospace">BED 1</text>
        <text x="155" y="55" fontSize="6" fill="#4A5552" fontFamily="monospace">BED 2</text>
        <text x="115" y="110" fontSize="6" fill="#4A5552" fontFamily="monospace">LIVING</text>
      </svg>);

  }
  if (rooms === 3) {
    return (
      <svg viewBox="0 0 200 150" preserveAspectRatio="xMidYMid meet">
        <rect x="10" y="20" width="180" height="110" fill={fill} stroke={stroke} strokeWidth={wallW} />
        <line x1="70" y1="20" x2="70" y2="130" stroke={stroke} strokeWidth={wallW} />
        <line x1="130" y1="20" x2="130" y2="130" stroke={stroke} strokeWidth={wallW} />
        <line x1="70" y1="75" x2="190" y2="75" stroke={stroke} strokeWidth={wallW} />
        <line x1="40" y1="55" x2="70" y2="55" stroke={stroke} strokeWidth={wallW} />
        <line x1="40" y1="90" x2="70" y2="90" stroke={stroke} strokeWidth={wallW} />
        <text x="18" y="40" fontSize="6" fill="#4A5552" fontFamily="monospace">HALL</text>
        <text x="18" y="75" fontSize="6" fill="#4A5552" fontFamily="monospace">SAN</text>
        <text x="18" y="115" fontSize="6" fill="#4A5552" fontFamily="monospace">KIT</text>
        <text x="85" y="50" fontSize="6" fill="#4A5552" fontFamily="monospace">BED 1</text>
        <text x="145" y="50" fontSize="6" fill="#4A5552" fontFamily="monospace">BED 2</text>
        <text x="85" y="105" fontSize="6" fill="#4A5552" fontFamily="monospace">LIVING</text>
        <text x="145" y="105" fontSize="6" fill="#4A5552" fontFamily="monospace">BED 3</text>
      </svg>);

  }
  // 4
  return (
    <svg viewBox="0 0 200 150" preserveAspectRatio="xMidYMid meet">
      <rect x="10" y="20" width="180" height="110" fill={fill} stroke={stroke} strokeWidth={wallW} />
      <line x1="60" y1="20" x2="60" y2="130" stroke={stroke} strokeWidth={wallW} />
      <line x1="110" y1="20" x2="110" y2="130" stroke={stroke} strokeWidth={wallW} />
      <line x1="160" y1="20" x2="160" y2="130" stroke={stroke} strokeWidth={wallW} />
      <line x1="60" y1="75" x2="190" y2="75" stroke={stroke} strokeWidth={wallW} />
      <line x1="10" y1="55" x2="60" y2="55" stroke={stroke} strokeWidth={wallW} />
      <line x1="10" y1="95" x2="60" y2="95" stroke={stroke} strokeWidth={wallW} />
      <text x="20" y="40" fontSize="5" fill="#4A5552" fontFamily="monospace">HALL</text>
      <text x="20" y="78" fontSize="5" fill="#4A5552" fontFamily="monospace">SAN</text>
      <text x="20" y="115" fontSize="5" fill="#4A5552" fontFamily="monospace">KIT</text>
      <text x="72" y="50" fontSize="5" fill="#4A5552" fontFamily="monospace">BED 1</text>
      <text x="120" y="50" fontSize="5" fill="#4A5552" fontFamily="monospace">BED 2</text>
      <text x="170" y="50" fontSize="5" fill="#4A5552" fontFamily="monospace">BED 3</text>
      <text x="72" y="105" fontSize="5" fill="#4A5552" fontFamily="monospace">LIVING</text>
      <text x="120" y="105" fontSize="5" fill="#4A5552" fontFamily="monospace">BED 4</text>
      <text x="170" y="105" fontSize="5" fill="#4A5552" fontFamily="monospace">DIN</text>
    </svg>);

};

const FloorPlateSVG = ({ floor }) => {
  // Schematic plan of the whole floor (4–5 apartments around a core)
  const stroke = "#3D3933";
  const acc = "#E1B778";
  return (
    <svg viewBox="0 0 480 240" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%', padding: 12 }}>
      <rect x="20" y="30" width="440" height="180" fill="#fff" stroke={stroke} strokeWidth="1.6" />
      {/* core */}
      <rect x="200" y="100" width="80" height="60" fill="rgba(225,183,120,0.18)" stroke={stroke} strokeWidth="1.4" />
      <text x="240" y="135" fontSize="9" textAnchor="middle" fill="#5A554C" fontFamily="monospace">CORE · LIFTS</text>
      {/* 4 apts around */}
      <line x1="20" y1="120" x2="200" y2="120" stroke={stroke} strokeWidth="1.4" />
      <line x1="280" y1="120" x2="460" y2="120" stroke={stroke} strokeWidth="1.4" />
      <line x1="120" y1="30" x2="120" y2="100" stroke={stroke} strokeWidth="1.4" />
      <line x1="360" y1="30" x2="360" y2="100" stroke={stroke} strokeWidth="1.4" />
      <line x1="120" y1="160" x2="120" y2="210" stroke={stroke} strokeWidth="1.4" />
      <line x1="360" y1="160" x2="360" y2="210" stroke={stroke} strokeWidth="1.4" />
      <text x="70" y="75" fontSize="10" textAnchor="middle" fill="#3D3933" fontFamily="var(--font-display)" fontWeight="700">A1</text>
      <text x="240" y="65" fontSize="10" textAnchor="middle" fill="#3D3933" fontFamily="var(--font-display)" fontWeight="700">A2</text>
      <text x="410" y="75" fontSize="10" textAnchor="middle" fill="#3D3933" fontFamily="var(--font-display)" fontWeight="700">A3</text>
      <text x="70" y="185" fontSize="10" textAnchor="middle" fill="#3D3933" fontFamily="var(--font-display)" fontWeight="700">A4</text>
      <text x="240" y="195" fontSize="10" textAnchor="middle" fill="#3D3933" fontFamily="var(--font-display)" fontWeight="700">A5</text>
      <text x="410" y="185" fontSize="10" textAnchor="middle" fill="#3D3933" fontFamily="var(--font-display)" fontWeight="700">A6</text>
      <circle cx="240" cy="20" r="5" fill={acc} />
      <text x="240" y="14" fontSize="8" textAnchor="middle" fill="#5A554C" fontFamily="monospace">N</text>
    </svg>);

};

const Plans = ({ lang }) => {
  if (!window.SITE_DATA || !window.SITE_DATA.plans || !window.SITE_DATA.plans.sections) {
    return <div className="container">Loading...</div>;
  }

  const t = window.SITE_DATA.plans[lang];
  const sections = window.SITE_DATA.plans.sections;
  const [active, setActive] = useState(1);
  const [lightbox, setLightbox] = useState(null);

  const cur = sections.find((s) => s.id === active);
  const counts = { 1: 0, 2: 0, 3: 0, 4: 0 };

  if (!cur) {
    console.error('Section not found:', active, 'Available sections:', sections);
    return null;
  }

  cur.apts.forEach((a) => counts[a.rooms]++);

  const fmtArea = (a) => a.toFixed(2).replace('.', ',');
  const roomsLabel = (r) => `${r}-${t.roomsShort}`;

  // Close lightbox on Esc
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') setLightbox(null);
    };
    if (lightbox) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [lightbox]);

  return (
    <section className="section section--alt" id="plans">
      <div className="container">
        <div className="section-head reveal">
          <div className="kicker">{t.kicker}</div>
          <h2 className="plans-title">{t.title}</h2>
          <p className="section-sub">{t.sub}</p>
        </div>

        <div className="sec-tabs reveal">
          <span className="sec-tabs-label">{t.sectionLabel}</span>
          {sections && sections.map((s) =>
          <button
            key={s.id}
            className={`sec-tab${s.id === active ? ' active' : ''}`}
            onClick={() => {
              console.log('Setting active section:', s.id);
              setActive(s.id);
            }}>

              {s.id}<span className="sec-tab-count">{s.apts ? s.apts.length : 0}</span>
            </button>
          )}
          <a href="assets/Альбом планировок.pdf" target="_blank" rel="noopener" className="plans-album-cta sec-tabs-cta">
            <Icon name="arrow" size={14} /> {t.albumCta}
          </a>
        </div>

        <div className="sec-panel" key={`section-${cur.id}-${active}`}>
          <div className="sec-stats">
            {[1, 2, 3, 4].map((k) => counts[k] > 0 &&
            <span key={k} className={`sec-stat-pill k${k}`}>
                <b>{counts[k]}</b> · {roomsLabel(k)}
              </span>
            )}
            <span className="sec-stat-total">{cur.apts.length} {lang === 'ru' ? 'квартир на этаже' : 'қабатта пәтер'}</span>
          </div>

          <div className="floor-banner">
            <div className="floor-banner-label">{t.floorLabel} · {t.sectionLabel} {cur.id}</div>
            <img
              src={cur.floor}
              alt={`${t.floorLabel} ${cur.id}`}
              onClick={() => setLightbox(cur.floor)} />
            
          </div>

          <div className="sec-apts-head">
            <h3>{t.aptsLabel}</h3>
            <span className="sec-apts-hint">{cur.apts.length} · {t.aptHint}</span>
          </div>

          <div className="sec-apts-grid">
            {cur.apts.map((a, i) =>
            <article key={i} className="apt-card">
                <div className="apt-thumb" onClick={() => setLightbox(a.f)}>
                  <img src={a.f} alt={`${roomsLabel(a.rooms)} ${fmtArea(a.area)} м²`} loading="lazy" />
                </div>
                <div className="apt-meta">
                  <div className="apt-row1">
                    <span className="apt-rooms">{roomsLabel(a.rooms)}</span>
                    <span className="apt-area">{fmtArea(a.area)}<span className="apt-unit">м²</span></span>
                  </div>
                  <div className="apt-row2">
                    <span className={`apt-tag k${a.rooms}`}>{a.rooms}К · {t.sectionLabel} {cur.id}</span>
                    <span className="apt-num">№ {String(i + 1).padStart(2, '0')}</span>
                  </div>
                </div>
              </article>
            )}
          </div>
        </div>

        <p className="plans-note">{t.priceNote}</p>

        {lightbox &&
        <div className="plans-lb" onClick={() => setLightbox(null)}>
            <button className="plans-lb-close" type="button">CLOSE · ESC</button>
            <img src={lightbox} alt="" />
          </div>
        }
      </div>
    </section>);

};

const Gallery = ({ lang, images }) => {
  const d = window.SITE_DATA.gallery[lang];
  const [active, setActive] = useState(null);
  return (
    <section className="section" id="gallery">
      <div className="container">
        <div className="section-head reveal">
          <div className="kicker">{d.kicker}</div>
          <h2>{d.title}</h2>
        </div>
        <div className="gallery-grid reveal">
          {images.map((src, i) =>
          <div key={i} className="gallery-item" onClick={() => setActive(src)}>
              <img src={src} alt="" />
            </div>
          )}
        </div>
      </div>
      {active &&
      <div onClick={() => setActive(null)} style={{
        position: 'fixed', inset: 0, background: 'rgba(22,56,43,0.92)',
        display: 'grid', placeItems: 'center', zIndex: 100, padding: 24, cursor: 'zoom-out'
      }}>
          <img src={active} alt="" style={{ maxWidth: '100%', maxHeight: '90vh', borderRadius: 8 }} />
        </div>
      }
    </section>);

};

const Progress = ({ lang }) => {
  const d = window.SITE_DATA.progress[lang];
  return (
    <section className="section section--ink" id="progress">
      <div className="container">
        <div className="section-head reveal">
          <div className="kicker">{d.kicker}</div>
          <h2>{d.title}</h2>
        </div>
        <div className="progress-list reveal">
          {d.stages.map((s, i) =>
          <div key={i} className={`progress-item ${s.done ? 'done' : ''} ${s.current ? 'current' : ''}`}>
              <div className="progress-q">{s.q}</div>
              <div className="progress-dot"></div>
              <div className="progress-t">{s.t}</div>
              <div className="progress-status">
                {s.done ? lang === 'ru' ? 'Завершено' : 'Аяқталды' :
              s.current ? lang === 'ru' ? 'В работе' : 'Орындалуда' :
              lang === 'ru' ? 'Запланировано' : 'Жоспарланған'}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

};

Object.assign(window, { Tech, Plans, Gallery, Progress, PlanSVG, FloorPlateSVG });