/* Life — HI-FI. Cinematic alternating panels with massive years.
   Polish: digit-by-digit year reveal, Ken-Burns slow-zoom on portrait placeholders,
   scroll-triggered reveals, sticky panel transitions.
*/

const HF_LIFE_MOMENTS = [
  { date: "1938",      place: "Çanakkale, Türkiye" },
  { date: "1950–1956", place: "Istanbul" },
  { date: "1960",      place: "Istanbul University" },
  { date: "1965",      place: "Istanbul" },
  { date: "1972",      place: "Ankara" },
  { date: "1982",      place: "Ankara" },
  { date: "1987",      place: "Worldwide" },
  { date: "2001",      place: "Dubbo, Australia · Istanbul" },
];

const LIFE_I18N = {
  scroll: { en: "scroll", tr: "kaydır", es: "desplázate", de: "scrollen", fr: "défiler", ru: "прокрутить", ja: "スクロール", zh: "滚动" },
  hero_sub: { en: "Across the ancient lands of Bukhara, a journey begins…", tr: "Buhara'nın kadim diyarlarında bir yolculuk başlar…", es: "A través de las antiguas tierras de Bujará, comienza un viaje…", de: "Über die alten Länder von Buchara hinweg beginnt eine Reise…", fr: "À travers les terres anciennes de Boukhara, un voyage commence…", ru: "Среди древних земель Бухары начинается путь…", ja: "ブハラの古き大地に、ひとつの旅が始まる…", zh: "在布哈拉古老的土地上，一段旅程就此开始……" },
  title_0: { en: "Born", tr: "Doğum", es: "Nacimiento", de: "Geburt", fr: "Naissance", ru: "Рождение", ja: "誕生", zh: "出生" },
  title_1: { en: "School years", tr: "Okul yılları", es: "Años de escuela", de: "Schuljahre", fr: "Années d'école", ru: "Школьные годы", ja: "学校時代", zh: "求学岁月" },
  title_2: { en: "Arabic & Persian philology", tr: "Arap ve Fars filolojisi", es: "Filología árabe y persa", de: "Arabische und persische Philologie", fr: "Philologie arabe et persane", ru: "Арабская и персидская филология", ja: "アラビア語・ペルシア語文献学", zh: "阿拉伯语与波斯语语文学" },
  title_3: { en: "Doctorate", tr: "Doktora", es: "Doctorado", de: "Promotion", fr: "Doctorat", ru: "Докторская степень", ja: "博士号", zh: "博士学位" },
  title_4: { en: "Associate Professor", tr: "Doçentlik", es: "Profesor titular", de: "Habilitation", fr: "Maître de conférences", ru: "Доцент", ja: "准教授", zh: "副教授" },
  title_5: { en: "Professor", tr: "Profesörlük", es: "Catedrático", de: "Professur", fr: "Professeur", ru: "Профессор", ja: "教授", zh: "教授" },
  title_6: { en: "Beyond the university", tr: "Üniversitenin ötesinde", es: "Más allá de la universidad", de: "Jenseits der Universität", fr: "Au-delà de l'université", ru: "За пределами университета", ja: "大学を超えて", zh: "大学之外" },
  title_7: { en: "Return to the eternal abode", tr: "Ebedî yurda dönüş", es: "Regreso a la morada eterna", de: "Rückkehr in die ewige Heimat", fr: "Retour à la demeure éternelle", ru: "Возвращение в вечную обитель", ja: "永遠の住まいへの帰還", zh: "归返永恒的居所" },
  body_0: { en: "Born on 14 April 1938 (13 Safar 1357 AH). A descendant of the Prophet (peace be upon him); his ancestors had migrated from Bukhara, Uzbekistan, carrying forward a legacy of faith and scholarship.", tr: "14 Nisan 1938'de (13 Safer 1357) dünyaya geldi. Peygamber (peace be upon him) soyundandı; ataları, iman ve ilim mirasını taşıyarak Özbekistan'ın Buhara şehrinden göç etmişti.", es: "Nació el 14 de abril de 1938 (13 Safar 1357 AH). Descendiente del Profeta (peace be upon him); sus antepasados habían emigrado desde Bukhara, Uzbekistán, llevando consigo un legado de fe y de saber.", de: "Geboren am 14. April 1938 (13 Safar 1357 AH). Ein Nachkomme des Propheten (peace be upon him); seine Vorfahren waren aus Bukhara, Usbekistan, eingewandert und trugen ein Erbe des Glaubens und der Gelehrsamkeit weiter.", fr: "Né le 14 avril 1938 (13 Safar 1357 AH). Descendant du Prophète (peace be upon him) ; ses ancêtres avaient émigré de Boukhara, en Ouzbékistan, perpétuant un héritage de foi et de savoir.", ru: "Родился 14 апреля 1938 года (13 Safar 1357 AH). Потомок Пророка (peace be upon him); его предки переселились из Бухары, Узбекистан, неся с собой наследие веры и учёности.", ja: "1938年4月14日（13 Safar 1357 AH）に生まれる。預言者 (peace be upon him) の末裔であり、その祖先は信仰と学問の遺産を携え、ウズベキスタンのブハラから移り住んだ。", zh: "生于1938年4月14日（13 Safar 1357 AH）。先知 (peace be upon him) 的后裔；其祖先自乌兹别克斯坦的布哈拉迁来，传承着信仰与学问的遗泽。" },
  body_1: { en: "Primary at Vezneciler School; secondary at Vefa High School. The first borrowed libraries; notebooks filled in two scripts.", tr: "İlkokulu Vezneciler Mektebi'nde, ortaöğrenimini Vefa Lisesi'nde okudu. İlk ödünç alınan kütüphaneler; iki yazıyla dolan defterler.", es: "Estudios primarios en la escuela Vezneciler; secundarios en el liceo Vefa. Las primeras bibliotecas prestadas; cuadernos llenos en dos escrituras.", de: "Grundschule in Vezneciler; weiterführende Schule am Gymnasium Vefa. Die ersten geliehenen Bibliotheken; Hefte, gefüllt in zwei Schriften.", fr: "Études primaires à l'école Vezneciler ; secondaires au lycée Vefa. Les premières bibliothèques empruntées ; des cahiers remplis en deux écritures.", ru: "Начальная школа в Везнеджилер; средняя — лицей Вефа. Первые книги, взятые из библиотек; тетради, исписанные двумя письменностями.", ja: "初等教育はヴェズネジレル校、中等教育はヴェファ高校で受けた。初めて借りた蔵書の数々、二つの文字で埋まっていく手帳。", zh: "小学就读于韦兹内吉莱尔学校，中学就读于韦法中学。最初借阅的座座书库；以两种文字写满的笔记本。" },
  body_2: { en: "Graduated from the Department of Arabic and Persian Philology. The years that would shape his command of four languages had begun.", tr: "Arap ve Fars Filolojisi Bölümü'nden mezun oldu. Dört dile olan hâkimiyetini şekillendirecek yıllar başlamıştı.", es: "Se graduó en el Departamento de Filología Árabe y Persa. Habían comenzado los años que forjarían su dominio de cuatro lenguas.", de: "Abschluss am Institut für Arabische und Persische Philologie. Die Jahre, die seine Beherrschung von vier Sprachen prägen sollten, hatten begonnen.", fr: "Diplômé du Département de philologie arabe et persane. Avaient commencé les années qui allaient forger sa maîtrise de quatre langues.", ru: "Окончил отделение арабской и персидской филологии. Начались годы, которым предстояло сформировать его владение четырьмя языками.", ja: "アラビア語・ペルシア語文献学科を卒業。四つの言語に通じる素養を形づくる歳月が始まっていた。", zh: "毕业于阿拉伯语与波斯语语文学系。那些将塑造他通晓四种语言的岁月已然开始。" },
  body_3: { en: "Earned his PhD. The first formal step in what would become a 27-year chapter at the Faculty of Theology, Ankara University.", tr: "Doktorasını tamamladı. Ankara Üniversitesi İlahiyat Fakültesi'nde yirmi yedi yıl sürecek bölümün ilk resmî adımı.", es: "Obtuvo su doctorado. El primer paso formal de lo que sería un capítulo de 27 años en la Facultad de Teología de la Universidad de Ankara.", de: "Er erwarb seinen Doktortitel. Der erste formale Schritt in ein 27 Jahre währendes Kapitel an der Theologischen Fakultät der Universität Ankara.", fr: "Il obtint son doctorat. Le premier pas officiel de ce qui allait devenir un chapitre de 27 ans à la Faculté de théologie de l'Université d'Ankara.", ru: "Защитил докторскую диссертацию. Первый официальный шаг в том, что станет 27-летней главой на богословском факультете Университета Анкары.", ja: "博士号を取得。アンカラ大学神学部での二十七年に及ぶ歩みの、最初の正式な一歩であった。", zh: "取得博士学位。这是他在安卡拉大学神学院长达二十七年篇章的第一个正式步伐。" },
  body_4: { en: "Awarded with the thesis Hacı Bektâş-ı Velî: Makalât — a study that placed him within the longest current of Anatolian Sufi thought.", tr: "Hacı Bektâş-ı Velî: Makalât adlı teziyle doçentlik unvanını aldı — onu Anadolu tasavvuf düşüncesinin en köklü çizgisine yerleştiren bir çalışma.", es: "Recibió el título con la tesis Hacı Bektâş-ı Velî: Makalât, un estudio que lo situó dentro de la corriente más antigua del pensamiento sufí de Anatolia.", de: "Ausgezeichnet mit der Arbeit Hacı Bektâş-ı Velî: Makalât — eine Studie, die ihn in die älteste Strömung des anatolischen Sufi-Denkens einreihte.", fr: "Distingué pour sa thèse Hacı Bektâş-ı Velî: Makalât — une étude qui l'inscrivit dans le plus ancien courant de la pensée soufie anatolienne.", ru: "Удостоен звания за диссертацию Hacı Bektâş-ı Velî: Makalât — труд, поставивший его в ряд самого древнего течения анатолийской суфийской мысли.", ja: "学位論文『Hacı Bektâş-ı Velî: Makalât』により称号を授与された——彼をアナトリア・スーフィズム思想の最も古い系譜へと位置づけた研究である。", zh: "凭论文《Hacı Bektâş-ı Velî: Makalât》获此殊荣——这部著作将他置于安纳托利亚苏非思想最为悠远的脉络之中。" },
  body_5: { en: "Awarded the title of Professor. By now an authority across Tafsīr, Ḥadīth and Taṣawwuf — through both academic and traditional scholarship.", tr: "Profesörlük unvanını aldı. Artık hem akademik hem de geleneksel ilim yoluyla Tefsir, Hadis ve Tasavvuf alanlarında bir otoriteydi.", es: "Recibió el título de Profesor. Para entonces, una autoridad en Tafsīr, Ḥadīth y Taṣawwuf, tanto por la vía académica como por la tradicional.", de: "Ihm wurde der Titel des Professors verliehen. Inzwischen eine Autorität in Tafsīr, Ḥadīth und Taṣawwuf — durch akademische wie auch traditionelle Gelehrsamkeit.", fr: "Il reçut le titre de Professeur. Désormais une autorité en Tafsīr, Ḥadīth et Taṣawwuf — par la voie académique comme par la voie traditionnelle.", ru: "Удостоен звания профессора. К тому времени — авторитет в области Tafsīr, Ḥadīth и Taṣawwuf, как в академической, так и в традиционной науке.", ja: "教授の称号を授与された。この頃には、学術と伝統の両方の学問を通じて、Tafsīr・Ḥadīth・Taṣawwuf にわたる権威となっていた。", zh: "获授教授头衔。此时他已通过学院与传统两途的学问，成为 Tafsīr、Ḥadīth 与 Taṣawwuf 诸领域的权威。" },
  body_6: { en: "After a notable chapter at Ankara University, he devoted himself fully to advancing educational and cultural initiatives across communities worldwide.", tr: "Ankara Üniversitesi'ndeki dikkate değer bir dönemin ardından, kendisini bütünüyle dünya genelindeki toplumlarda eğitim ve kültür çalışmalarını ileri taşımaya adadı.", es: "Tras un destacado capítulo en la Universidad de Ankara, se entregó por completo a impulsar iniciativas educativas y culturales en comunidades de todo el mundo.", de: "Nach einem bemerkenswerten Kapitel an der Universität Ankara widmete er sich ganz der Förderung von Bildungs- und Kulturinitiativen in Gemeinschaften weltweit.", fr: "Après un remarquable chapitre à l'Université d'Ankara, il se consacra pleinement à promouvoir des initiatives éducatives et culturelles au sein de communautés du monde entier.", ru: "После заметной главы в Университете Анкары он всецело посвятил себя развитию образовательных и культурных начинаний в сообществах по всему миру.", ja: "アンカラ大学での特筆すべき歳月を経て、彼は世界各地の共同体における教育・文化の営みを推し進めることに全身全霊を捧げた。", zh: "在安卡拉大学度过卓著的一段时光之后，他全心投入于在世界各地的社群中推进教育与文化事业。" },
  body_7: { en: "Returned to his eternal abode on 4 February 2001 (10 Dhu'l-Qa'dah 1421 AH) in Dubbo, Australia, and was later laid to rest at Eyüp Sultan Cemetery in Istanbul.", tr: "4 Şubat 2001'de (10 Zilkâde 1421) Avustralya'nın Dubbo şehrinde ebedî yurduna döndü; sonradan İstanbul'da Eyüp Sultan Mezarlığı'na defnedildi.", es: "Regresó a su morada eterna el 4 de febrero de 2001 (10 Dhu'l-Qa'dah 1421 AH) en Dubbo, Australia, y más tarde fue sepultado en el cementerio de Eyüp Sultan en Estambul.", de: "Er kehrte am 4. Februar 2001 (10 Dhu'l-Qa'dah 1421 AH) in Dubbo, Australien, in seine ewige Heimat zurück und wurde später auf dem Friedhof Eyüp Sultan in Istanbul zur letzten Ruhe gebettet.", fr: "Il retourna à sa demeure éternelle le 4 février 2001 (10 Dhu'l-Qa'dah 1421 AH) à Dubbo, en Australie, et fut plus tard inhumé au cimetière d'Eyüp Sultan à Istanbul.", ru: "Вернулся в свою вечную обитель 4 февраля 2001 года (10 Dhu'l-Qa'dah 1421 AH) в Даббо, Австралия, и позднее был погребён на кладбище Эюп Султан в Стамбуле.", ja: "2001年2月4日（10 Dhu'l-Qa'dah 1421 AH）、オーストラリアのダボにて永遠の住まいへと帰った。のちにイスタンブールのエユップ・スルタン墓地に埋葬された。", zh: "于2001年2月4日（10 Dhu'l-Qa'dah 1421 AH）在澳大利亚的达博归返永恒的居所，后安葬于伊斯坦布尔的埃郁普苏丹墓园。" },
};
function lifeT(key, lang) { const e = LIFE_I18N[key]; return (e && (e[lang] || e.en)) || ""; }

/* AnimatedYear — splits the date string into digits, each fades up on reveal */
function AnimatedYear({ text, fontSize, color, accent }) {
  return (
    <span className="hf-year" style={{ fontSize, letterSpacing: "-0.04em", lineHeight: 0.88,
      color, fontFamily: "var(--serif)", fontWeight: 300,
      fontVariationSettings: '"opsz" 144, "SOFT" 30' }}>
      {text.split("").map((c, i) => (
        <span key={i} style={{
          animationDelay: `${i * 90}ms`,
          color: c === "–" || c === "—" ? accent : undefined,
        }}>{c}</span>
      ))}
    </span>
  );
}

const HF_BIO_PHOTOS = ["uploads/photos/bio-1.jpg", "uploads/photos/bio-2.jpg", "uploads/photos/bio-3.jpg"];

function LifeHiFi({ mode = "desktop", accent = "#B89968", showPortrait = true }) {
  const mobile = mode === "mobile";
  const rootRef = React.useRef(null);
  const [lang] = (typeof useLang === "function" ? useLang() : ["en"]);
  const nav = (typeof useT === "function" ? useT() : {});
  const lt = (k) => lifeT(k, lang);

  React.useEffect(() => {
    const root = rootRef.current; if (!root) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("is-in"); io.unobserve(e.target); } });
    }, { root, threshold: 0.18, rootMargin: "0px 0px -8% 0px" });
    root.querySelectorAll(".hf-reveal").forEach(t => io.observe(t));
    return () => io.disconnect();
  }, []);

  return (
    <div ref={rootRef} className="cw-frame" style={{ overflowY: "auto", overflowX: "hidden" }}>
      <TopNav current="Life" mobile={mobile} accent={accent} />

      {/* Cinematic hero */}
      <section style={{ padding: mobile ? "60px 22px 40px" : "120px 64px 60px", borderBottom: "1px solid var(--ink)" }}>
        <span className="hf-eyebrow-rule hf-rise" style={{ animationDelay: "120ms" }}>05  /  {nav.life || "Life"}  ·  {lt("scroll")}  ↓</span>
        <h1 className="serif hf-rise" style={{
          fontWeight: 300, fontSize: mobile ? 128 : 340, lineHeight: 0.86, letterSpacing: "-0.045em",
          margin: "12px 0 0", fontVariationSettings: '"opsz" 144, "SOFT" 30',
          animationDelay: "300ms",
        }}>
          1938<span style={{ color: accent }}>—</span><br/>
          2001<span style={{ color: accent, fontStyle: "italic", fontVariationSettings: '"opsz" 9, "SOFT" 100' }}>.</span>
        </h1>
        <p className="serif italic hf-fade" style={{
          fontSize: mobile ? 20 : 32, color: "var(--ink-soft)", margin: "32px 0 0",
          maxWidth: 800, lineHeight: 1.3,
          fontVariationSettings: '"opsz" 9, "SOFT" 100',
          animationDelay: "1200ms",
        }}>
          {lt("hero_sub")}
        </p>
      </section>

      {/* Alternating panels with Ken-Burns image + digit reveal */}
      <section>
        {HF_LIFE_MOMENTS.map((m, i) => {
          const dark = i % 2 === 0;
          const imageOnRight = i % 2 === 1;
          const photo = HF_BIO_PHOTOS[i];

          return (
            <article
              key={i}
              className="hf-reveal"
              style={{
                background: dark ? "var(--ink)" : "var(--bg-warm)",
                color: dark ? "var(--bg)" : "var(--ink)",
                padding: mobile ? "60px 22px" : "140px 64px",
                display: "grid",
                gridTemplateColumns: mobile ? "1fr" : (imageOnRight ? "1fr 1.1fr" : "1.1fr 1fr"),
                gap: mobile ? 28 : 80,
                alignItems: "center",
                borderBottom: dark ? "1px solid var(--gold-deep)" : "1px solid var(--hairline)",
                position: "relative",
                overflow: "hidden",
              }}
            >
              {/* Text column */}
              <div style={{ order: !mobile && imageOnRight ? 1 : 1, position: "relative", zIndex: 2 }}>
                <span className="eyebrow" style={{ color: dark ? "var(--gray-light)" : "var(--gray-warm)" }}>
                  — {String(i + 1).padStart(2, "0")}  ·  {m.place}
                </span>
                <div style={{ margin: "8px 0 24px" }}>
                  <AnimatedYear
                    text={m.date}
                    fontSize={mobile ? 76 : (m.date.includes("–") ? 132 : 220)}
                    color={dark ? "var(--bg)" : "var(--ink)"}
                    accent={accent}
                  />
                </div>
                <h3 className="serif italic" style={{
                  fontSize: mobile ? 22 : 34, fontWeight: 350,
                  lineHeight: 1.25, margin: "0 0 18px", color: accent,
                  fontVariationSettings: '"opsz" 9, "SOFT" 100',
                }}>{lt("title_" + i)}</h3>
                <p style={{
                  fontSize: mobile ? 15 : 18, lineHeight: 1.7,
                  maxWidth: 480, margin: 0,
                  color: dark ? "rgba(250,250,247,0.78)" : "var(--ink-soft)",
                  textWrap: "pretty",
                }}>{lt("body_" + i)}</p>
              </div>

              {/* Mobile: show the page photo inline (md.5) — tap to enlarge */}
              {mobile && showPortrait && photo && (
                <div onClick={() => window.openLightbox && window.openLightbox(photo)}
                  style={{ aspectRatio: "4/5", overflow: "hidden", cursor: "zoom-in",
                    border: dark ? "1px solid rgba(255,255,255,0.06)" : "1px solid var(--hairline)" }}>
                  <img src={photo} alt={lt("title_" + i)} loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
                </div>
              )}

              {/* Portrait placeholder column — Ken-Burns slow zoom on reveal */}
              {!mobile && (
                <div style={{
                  order: imageOnRight ? 2 : 0,
                  aspectRatio: "4/5",
                  position: "relative",
                  overflow: "hidden",
                  border: dark ? "1px solid rgba(255,255,255,0.06)" : "1px solid var(--hairline)",
                }}>
                  {showPortrait ? (
                    <>
                      <div className="hf-kenburns hf-portrait" style={{ position: "absolute", inset: 0 }}>
                        {photo ? (
                          <img src={photo} alt={lt("title_" + i)} loading="lazy" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
                        ) : (
                        <svg viewBox="0 0 320 400" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
                          <defs>
                            <linearGradient id={`hfLifeGrad-${i}`} x1="0" y1="0" x2="0" y2="1">
                              <stop offset="0%"  stopColor={dark ? "#3A3530" : "#9C8E78"} stopOpacity="0.7" />
                              <stop offset="60%" stopColor={dark ? "#181612" : "#6B6357"} stopOpacity="0.9" />
                              <stop offset="100%" stopColor={dark ? "#0A0908" : "#3F3A33"} stopOpacity="1" />
                            </linearGradient>
                          </defs>
                          <rect width="320" height="400" fill={`url(#hfLifeGrad-${i})`} />
                          {/* Soft elliptical light */}
                          <ellipse cx="120" cy="140" rx="80" ry="100" fill={dark ? "#4A4035" : "#C9BBA1"} opacity="0.22" />
                          <ellipse cx="160" cy="220" rx="180" ry="160" fill="#000" opacity="0.18" />
                        </svg>
                        )}
                      </div>
                      <div className="hf-grain" />
                      <span style={{
                        position: "absolute", right: 18, bottom: 14, zIndex: 3,
                        fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 11,
                        color: dark ? "rgba(255,255,255,0.42)" : "rgba(255,255,255,0.6)",
                        fontVariationSettings: '"opsz" 9, "SOFT" 100'
                      }}>{m.date}</span>
                    </>
                  ) : (
                    <div style={{ position: "absolute", inset: 0, background: dark ? "rgba(255,255,255,0.04)" : "var(--bg-deep)" }} />
                  )}
                </div>
              )}
            </article>
          );
        })}
      </section>

      <SiteFooter mobile={mobile} accent={accent} />
    </div>
  );
}

Object.assign(window, { LifeHiFi });
