window.__profileDataReady.then((SITE_PROFILE) => {
    const PROJECTS = SITE_PROFILE.projects || window.PROJECTS || [];
    const JOBS = SITE_PROFILE.jobs || window.JOBS || [];
    const SKILLS = SITE_PROFILE.skills || window.SKILLS || [];
    const EDUCATION = SITE_PROFILE.education || [];
    const MATRIX_COLS = (SITE_PROFILE.roleMatrix && SITE_PROFILE.roleMatrix.cols) || window.MATRIX_COLS || [];
    const MATRIX_ROWS = (SITE_PROFILE.roleMatrix && SITE_PROFILE.roleMatrix.rows) || window.MATRIX_ROWS || [];
    const TWEAK_DEFAULTS = SITE_PROFILE.tweaks || window.TWEAK_DEFAULTS || {};

    function setText(selector, value) {
      const el = document.querySelector(selector);
      if (el && value) el.textContent = value;
    }

    function setHtml(selector, value) {
      const el = document.querySelector(selector);
      if (el && value) el.innerHTML = value;
    }

    function hydrateStaticProfileContent() {
      const hero = SITE_PROFILE.hero || {};
      const sections = SITE_PROFILE.sections || {};
      setHtml('.hero-name', hero.nameHtml);
      setText('.hero-title', hero.title);
      setHtml('.hero-tagline', hero.taglineHtml);
      setText('#portfolio .section-sub.prominent', sections.portfolioIntro);
      setText('#roles .section-sub.prominent', sections.roleIntro);
      setText('#cultural-fit .section-sub.prominent', sections.culturalFitIntro);
      setText('#blog .section-sub.prominent', sections.blogIntro);
      setHtml('#contact .contact-title', sections.contactTitleHtml);
      setText('#contact .contact-sub', sections.contactSubtitle);

      const impact = document.getElementById('impact');
      if (impact && Array.isArray(hero.impactStats)) {
        impact.innerHTML = hero.impactStats.map((item) => (
          '<div class="impact-item" onclick="openProjectModal(\'' + item.projectId + '\')">' +
          '<div class="impact-num">' + item.valueHtml + '</div>' +
          '<div class="impact-desc">' + item.label + '</div>' +
          '</div>'
        )).join('');
      }
    }

    hydrateStaticProfileContent();

function RoleMatrix() {
      return (
        <div className="role-matrix-wrap">
          <div className="role-matrix-header">
            <div className="role-matrix-header-cell"></div>
            {MATRIX_COLS.map(col => (
              <div key={col.id} className={`role-matrix-header-cell ${col.accent ? 'accent' : ''}`}>{col.label}</div>
            ))}
          </div>
          {MATRIX_ROWS.map(row => (
            <div key={row.label} className="role-matrix-row">
              <div className="role-matrix-row-label">
                <div className="row-label-title">{row.label}</div>
                <div className="row-label-sub">{row.sub}</div>
              </div>
              {MATRIX_COLS.map(col => {
                const cell = row.cells[col.id];
                return (
                  <div key={col.id} className={`role-matrix-cell ${cell.fit}`}>
                    {cell.badge && <div className="cell-preferred-badge">{cell.badge}</div>}

                    <div className={`cell-role-title ${cell.fit === 'weak' ? 'muted' : ''}`}>{cell.title}</div>
                    <ul className="cell-bullets">
                      {cell.bullets.map((b, i) => <li key={i}>{b}</li>)}
                    </ul>
                  </div>
                );
              })}
            </div>
          ))}
          <div className="role-matrix-note">
            {(SITE_PROFILE.roleMatrix && SITE_PROFILE.roleMatrix.note) || "Ivo's preference: small-to-midsize team leadership with hands-on execution over paper-pushing and slideware. The more complex and ambiguous the problem, the better."}
          </div>
        </div>
      );
    }

    const COMP_DATA = (SITE_PROFILE.compensation && SITE_PROFILE.compensation.data) || window.COMP_DATA || [];
    const COMP_TARGET = (SITE_PROFILE.compensation && SITE_PROFILE.compensation.targetEur) || window.COMP_TARGET || 145000;

    const BLOGS = SITE_PROFILE.blogs || window.BLOGS || [];

    function BlogGrid({ onOpen }) {
      return (
        <div className="blog-grid">
          {BLOGS.map(blog => (
            <div key={blog.id} className="blog-card" onClick={() => onOpen(blog)}>
              <img src={blog.image} alt={blog.title} className="blog-card-img" />
              <div className="blog-card-content">
                <div className="blog-date">{blog.date}</div>
                <h4 className="blog-title">{blog.title}</h4>
                <p className="blog-excerpt">{blog.excerpt}</p>
                <div className="blog-read-more">Read Article</div>
              </div>
            </div>
          ))}
        </div>
      );
    }

    function CompChart() {
      const svgRef = React.useRef(null);
      const [tooltip, setTooltip] = React.useState(null);
      const [animated, setAnimated] = React.useState(false);
      React.useEffect(() => { setTimeout(() => setAnimated(true), 100); }, []);

      const W = 900, H = 340;
      const padL = 72, padR = 48, padT = 48, padB = 48;
      const chartW = W - padL - padR;
      const chartH = H - padT - padB;

      const minVal = 0;
      const maxVal = COMP_TARGET * 1.1;
      const years = COMP_DATA.map(d => d.year);
      const minYear = years[0], maxYear = years[years.length - 1];

      const xScale = y => padL + ((y - minYear) / (maxYear - minYear)) * chartW;
      const yScale = v => padT + chartH - ((v - minVal) / (maxVal - minVal)) * chartH;

      const pts = COMP_DATA.map(d => ({ x: xScale(d.year), y: yScale(d.eur), ...d }));

      const linePath = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ');
      const areaPath = `${linePath} L ${pts[pts.length - 1].x} ${padT + chartH} L ${pts[0].x} ${padT + chartH} Z`;

      const targetY = yScale(COMP_TARGET);
      const growth = Math.round((COMP_DATA[COMP_DATA.length - 1].eur / COMP_DATA[0].eur - 1) * 100);

      const fmtK = v => `€${Math.round(v / 1000)}k`;

      const yTicks = [0, 30000, 60000, 90000, 120000, 150000];

      return (
        <div className="comp-chart-wrap">
          <div className="comp-chart-header">
            <div className="comp-summary-stats">
              <div className="comp-stat">
                <div className="comp-stat-num">{(SITE_PROFILE.compensation && SITE_PROFILE.compensation.lastCompensationLabel) || '€109k cash + €25k equity'}</div>
                <div className="comp-stat-label">Last job compensation</div>
              </div>

              <div className="comp-stat">
                <div className="comp-stat-num" style={{ color: 'oklch(0.75 0.14 145)' }}>{(SITE_PROFILE.compensation && SITE_PROFILE.compensation.targetLabel) || fmtK(COMP_TARGET)}</div>
                <div className="comp-stat-label">Compensation expectations</div>
              </div>
            </div>
          </div>
          <div className="comp-chart-svg-wrap">
            {tooltip && (
              <div className={`comp-tooltip visible`} style={{
                left: tooltip.flip ? tooltip.x - 12 : tooltip.x + 12,
                transform: tooltip.flip ? 'translateX(-100%)' : 'none',
                top: tooltip.y - 48
              }}>
                <div className="comp-tooltip-year">{tooltip.year} · {tooltip.note}</div>
                <div className="comp-tooltip-val">{fmtK(tooltip.eur)}</div>
                {tooltip.delta > 0 && <div className="comp-tooltip-delta">+{tooltip.delta}% vs prior year</div>}
              </div>
            )}
            <svg ref={svgRef} viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
              <defs>
                <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="oklch(0.72 0.18 55)" stopOpacity="0.18" />
                  <stop offset="100%" stopColor="oklch(0.72 0.18 55)" stopOpacity="0.01" />
                </linearGradient>
                <linearGradient id="targetGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="oklch(0.75 0.14 145)" stopOpacity="0.12" />
                  <stop offset="100%" stopColor="oklch(0.75 0.14 145)" stopOpacity="0.01" />
                </linearGradient>
                <clipPath id="chartClip">
                  <rect x={padL} y={padT} width={animated ? chartW : 0} height={chartH} style={{ transition: 'width 1.4s cubic-bezier(0.4,0,0.2,1)' }}>
                  </rect>
                </clipPath>
              </defs>

              {/* Grid lines */}
              {yTicks.map(v => (
                <g key={v}>
                  <line x1={padL} x2={padL + chartW} y1={yScale(v)} y2={yScale(v)}
                    stroke="rgba(255,255,255,0.05)" strokeWidth="1" />
                  <text x={padL - 8} y={yScale(v) + 4} textAnchor="end"
                    fontSize="10" fill="rgba(245,240,234,0.3)" fontFamily="DM Mono">
                    {fmtK(v)}
                  </text>
                </g>
              ))}

              {/* Year labels */}
              {COMP_DATA.filter((_, i) => i % 2 === 0 || i === COMP_DATA.length - 1).map(d => (
                <text key={d.year} x={xScale(d.year)} y={padT + chartH + 18}
                  textAnchor="middle" fontSize="10" fill="rgba(245,240,234,0.3)" fontFamily="DM Mono">
                  {d.year}
                </text>
              ))}

              {/* Target zone */}
              <rect x={padL} y={padT} width={chartW} height={targetY - padT}
                fill="oklch(0.75 0.14 145 / 0.03)" />
              <line x1={padL} x2={padL + chartW} y1={targetY} y2={targetY}
                stroke="oklch(0.75 0.14 145)" strokeWidth="1.5" strokeDasharray="6 4" opacity="0.7" />
              <text x={padL + chartW - 4} y={targetY - 7} textAnchor="end"
                fontSize="10" fill="oklch(0.75 0.14 145)" fontFamily="DM Mono" fontWeight="500">
                TARGET {(SITE_PROFILE.compensation && SITE_PROFILE.compensation.targetLabel) || fmtK(COMP_TARGET)}
              </text>

              {/* Inflection annotations */}
              {pts.filter(p => p.inflection).map(p => (
                <g key={p.year}>
                  <line x1={p.x} x2={p.x} y1={p.y - 16} y2={padT + 4}
                    stroke="rgba(255,255,255,0.06)" strokeWidth="1" strokeDasharray="3 3" />
                  <text x={p.x} y={padT - 4} textAnchor="middle"
                    fontSize="9" fill="rgba(245,240,234,0.35)" fontFamily="DM Mono">
                    {p.inflection}
                  </text>
                </g>
              ))}

              {/* Area fill */}
              <path d={areaPath} fill="url(#areaGrad)" clipPath="url(#chartClip)" />

              {/* Line */}
              <path d={linePath} fill="none"
                stroke="oklch(0.72 0.18 55)" strokeWidth="2.5"
                strokeLinejoin="round" strokeLinecap="round"
                clipPath="url(#chartClip)" />

              {/* Data points */}
              {pts.map((p, i) => {
                const prev = i > 0 ? COMP_DATA[i - 1].eur : null;
                const delta = prev ? Math.round((p.eur / prev - 1) * 100) : 0;
                return (
                  <circle key={p.year} cx={p.x} cy={p.y} r="5"
                    fill="var(--bg2)" stroke="oklch(0.72 0.18 55)" strokeWidth="2"
                    style={{ cursor: 'pointer' }}
                    onMouseEnter={e => {
                      const rect = svgRef.current.getBoundingClientRect();
                      const svgW = rect.width;
                      const scaleX = svgW / W;
                      const flip = i >= COMP_DATA.length - 2;
                      setTooltip({ ...p, delta, x: p.x * scaleX, y: p.y * scaleX, flip });
                    }}
                    onMouseLeave={() => setTooltip(null)}
                  />
                );
              })}

              {/* Last value label */}
              <text x={pts[pts.length - 1].x + 8} y={pts[pts.length - 1].y + 4}
                fontSize="11" fill="oklch(0.72 0.18 55)" fontFamily="DM Mono" fontWeight="500">
                {fmtK(COMP_DATA[COMP_DATA.length - 1].eur)}
              </text>
            </svg>
          </div>
          <div className="comp-footer-note">
            {(SITE_PROFILE.compensation && SITE_PROFILE.compensation.footerNote) || 'All figures shown in EUR equivalent at time of earning. Target compensation reflects senior product leadership expectations for 2025–26.'}
          </div>
        </div>
      );
    }

    // Render compensation chart
    const compEl = document.getElementById('comp-chart');
    if (compEl) {
      const compRoot = ReactDOM.createRoot(compEl);
      compRoot.render(<CompChart />);
    }

    // Add "Compensation" to nav
    // Render roles
    const rolesEl = document.getElementById('roles-grid');
    if (rolesEl) {
      rolesEl.className = '';
      const rolesRoot = ReactDOM.createRoot(rolesEl);
      rolesRoot.render(<RoleMatrix />);
    }

    function ProjectCard({ proj, onOpen }) {
      const isFullscreen = !!proj.video;
      const sizeClass = isFullscreen ? 'fullscreen' : proj.size;
      return (
        <div id={`proj-${proj.id}`} className={`proj-card ${sizeClass}`} onClick={() => onOpen(proj)}>
          <div className="proj-media">
            {proj.badge && <div className="moma-badge">{proj.badge}</div>}
            {proj.video ? (
              <video
                src={proj.video}
                autoPlay
                muted
                playsInline
                loop={proj.id !== 'iona-navis'}
                onLoadedMetadata={e => { if (proj.id === 'iona-navis') e.target.currentTime = 248; }}
                onEnded={e => { if (proj.id === 'iona-navis') { e.target.currentTime = 248; e.target.play(); } }}
              />
            ) : proj.image ? (
              <img src={proj.image} alt={proj.title} />
            ) : (
              <div className="proj-media-placeholder">
                <div className="proj-media-placeholder-label">{proj.title}</div>
                <div className="proj-media-upload"><span>Image / Video</span></div>
              </div>
            )}
          </div>
          {isFullscreen ? (
            <div className="mask-overlay">
              <div className="mask-content">
                <h5 className="mask-title">{proj.title}</h5>
                <div className="mask-frame" />
                <span className="mask-cta">Click to see more</span>
                <div className="mask-pills">
                  {proj.impacts.slice(0, 3).map(imp => (
                    <span key={imp} className="proj-impact-pill">{imp}</span>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div className="proj-inner">
              <h5 className="proj-title">{proj.title}</h5>
              <div className="proj-impacts">
                {proj.impacts.slice(0, 3).map(imp => (
                  <span key={imp} className="proj-impact-pill">{imp}</span>
                ))}
              </div>
              <div className="proj-see-more">See details</div>
            </div>
          )}
        </div>
      );
    }

    function CVItem({ job, idx }) {
      const [open, setOpen] = React.useState(false);
      return (
        <div className={`cv-item ${job.current ? 'current' : ''}`}>
          <div className="cv-left">
            <div className="cv-period">{job.period}</div>
            <div className="cv-location">{job.location}</div>
          </div>
          <div className="cv-dot"></div>
          <div className="cv-right">
            <div className="cv-company">{job.company}</div>
            <div className="cv-role">{job.role}</div>
            <ul className="cv-bullets">
              {job.bullets.map((b, i) => (
                <li key={i} dangerouslySetInnerHTML={{ __html: b.text }} />
              ))}
            </ul>
            {open && (
              <ul className="cv-bullets cv-extra open" style={{ marginTop: '12px' }}>
                {job.extra.map((b, i) => (
                  <li key={i} dangerouslySetInnerHTML={{ __html: b.text }} />
                ))}
              </ul>
            )}
            {job.extra.length > 0 && (
              <button className="cv-expand-btn" onClick={() => setOpen(!open)}>
                {open ? '↑ Less' : `↓ ${job.extra.length} more detail${job.extra.length > 1 ? 's' : ''}`}
              </button>
            )}
          </div>
        </div>
      );
    }

    function Carousel({ images }) {
      const [idx, setIdx] = React.useState(0);
      if (!images || images.length === 0) return null;
      const next = () => setIdx((prev) => (prev + 1) % images.length);
      const prev = () => setIdx((prev) => (prev - 1 + images.length) % images.length);

      React.useEffect(() => {
        const timer = setInterval(() => {
          setIdx((prev) => (prev + 1) % images.length);
        }, 3000);
        return () => clearInterval(timer);
      }, [images.length]);

      return (
        <div className="carousel-wrap">
          <div className="carousel-track" style={{ transform: `translateX(-${idx * 100}%)` }}>
            {images.map((src, i) => (
              <div className="carousel-slide" key={i}>
                <img src={src} alt="" className="carousel-img" />
              </div>
            ))}
          </div>
          <button className="carousel-btn carousel-prev" onClick={prev}>←</button>
          <button className="carousel-btn carousel-next" onClick={next}>→</button>
          <div className="carousel-dots">
            {images.map((_, i) => (
              <button key={i} className={`carousel-dot ${i === idx ? 'active' : ''}`} onClick={() => setIdx(i)} />
            ))}
          </div>
        </div>
      );
    }

    const { TweaksPanel, TweakSection, TweakRadio, TweakToggle } = window;



    const AUTO_PLAY_INTERVAL = 8000;
    const ITEM_HEIGHT = 80;
    const ITEM_WIDTH = 180;



    const wrap = (min, max, v) => {
      const rangeSize = max - min;
      return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
    };

	    function FeatureCarousel({ onOpen }) {
	      const { useState, useEffect, useCallback } = React;

	      const [step, setStep] = useState(0);
      const [isPaused, setIsPaused] = useState(false);
      const [isDesktop, setIsDesktop] = useState(window.innerWidth > 900);

      useEffect(() => {
        const handleResize = () => setIsDesktop(window.innerWidth > 900);

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
      }, []);

      const currentIndex = ((step % PROJECTS.length) + PROJECTS.length) % PROJECTS.length;

      const nextStep = useCallback(() => {
        setStep((prev) => prev + 1);
      }, []);

      const handleChipClick = (index) => {
        const diff = (index - currentIndex + PROJECTS.length) % PROJECTS.length;
        if (diff > 0) setStep((s) => s + diff);
      };

      useEffect(() => {
        if (isPaused) return;
        const interval = setInterval(nextStep, AUTO_PLAY_INTERVAL);
        return () => clearInterval(interval);
      }, [nextStep, isPaused]);

      const getCardStatus = (index) => {
        const diff = index - currentIndex;
        const len = PROJECTS.length;

        let normalizedDiff = diff;
        if (diff > len / 2) normalizedDiff -= len;
        if (diff < -len / 2) normalizedDiff += len;

        if (normalizedDiff === 0) return "active";
        if (normalizedDiff === -1) return "prev";
        if (normalizedDiff === 1) return "next";
        return "hidden";
      };

      return (
        <div className="fc-container">
          <div className="fc-wrapper">
            <div className="fc-left">
              <div className="fc-grad-top" />
              <div className="fc-grad-bot" />
              <div className="fc-items-wrap">
                {PROJECTS.map((feature, index) => {
                  const isActive = index === currentIndex;
                  const distance = index - currentIndex;
                  const wrappedDistance = wrap(
                    -(PROJECTS.length / 2),
                    PROJECTS.length / 2,
                    distance
                  );

                  return (
	                    <div
	                      key={`${feature.id}-nav`}
	                      style={{
	                        height: isDesktop ? "auto" : ITEM_HEIGHT,
	                        width: isDesktop ? "auto" : ITEM_WIDTH,
	                        position: isDesktop ? "relative" : "absolute",
	                        transform: isDesktop ? "none" : `translateX(${wrappedDistance * ITEM_WIDTH}px)`,
	                        opacity: isDesktop ? 1 : 1 - Math.abs(wrappedDistance) * 0.4,
	                        transition: "transform 360ms ease, opacity 360ms ease"
	                      }}
	                      className="fc-item-motion"
	                    >
                      <button
                        onClick={() => handleChipClick(index)}
                        onMouseEnter={() => setIsPaused(true)}
                        onMouseLeave={() => setIsPaused(false)}
                        className={"fc-btn " + (isActive ? "active" : "")}
                        style={{ width: isDesktop ? "auto" : ITEM_WIDTH - 40, justifyContent: 'center' }}
                      >
                        <span className="fc-label">{feature.title}</span>
                      </button>
	                    </div>
                  );

                })}
              </div>
            </div>

            <div className="fc-right">
              <div className="fc-cards">
                {PROJECTS.map((feature, index) => {
                  const status = getCardStatus(index);
                  const isActive = status === "active";
                  const isPrev = status === "prev";
                  const isNext = status === "next";

                  return (
	                    <div
	                      key={`${feature.id}-card`}
	                      style={{
	                        transform: `translateX(${isActive ? 0 : isPrev ? -100 : isNext ? 100 : 0}px) scale(${isActive ? 1 : isPrev || isNext ? 0.85 : 0.7}) rotate(${isPrev ? -3 : isNext ? 3 : 0}deg)`,
	                        opacity: isActive ? 1 : isPrev || isNext ? 0.4 : 0,
	                        zIndex: isActive ? 20 : isPrev || isNext ? 10 : 0,
	                        pointerEvents: isActive ? "auto" : "none",
	                        transition: "transform 420ms cubic-bezier(0.2, 0.8, 0.2, 1), opacity 300ms ease"
	                      }}
	                      className="fc-card"
	                    >
                      {feature.video ? (
                        <video src={feature.video} autoPlay loop muted playsInline className="fc-img" />
                      ) : (
                        <img src={feature.image} alt={feature.title} className="fc-img" />
                      )}

	                      {isActive && (
	                        <div
	                          key={`${feature.id}-overlay`}
	                          className="fc-card-overlay"
	                        >
	                          <div className="fc-card-badge">{feature.tag}</div>
	                          <div className="fc-impact-tags">
	                            {feature.impacts && feature.impacts.map((imp, i) => (
	                              <span key={i} className="fc-impact-tag">{imp}</span>
	                            ))}
	                          </div>
	                          <button className="fc-see-more" onClick={(e) => { e.stopPropagation(); onOpen(feature); }}>See details</button>
	                        </div>
	                      )}
	                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      );
    }

    function PortfolioApp() {

      const [modalProj, setModalProj] = React.useState(null);
      const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

      const openModal = (proj) => setModalProj(proj);
      const closeModal = () => { setModalProj(null); };

      return (
        <>
          <FeatureCarousel onOpen={openModal} />


          {/* CV Timeline */}
          <div style={{ display: 'none' }} id="cv-react-mount">
            {JOBS.map((job, i) => <CVItem key={i} job={job} idx={i} />)}
          </div>

          {/* Modal */}
          <div className={`modal-overlay ${modalProj ? 'open' : ''}`} onClick={(e) => { if (e.target.classList.contains('modal-overlay')) closeModal(); }}>
            {modalProj && (
              <div className={`modal ${(modalProj.youtube || modalProj.gallery) ? 'modal--wide' : ''}`} onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                  <div>
                    <div style={{ marginBottom: '10px' }}>
                      <span className={`proj-tag ${modalProj.tagClass || ''}`}>{modalProj.tag}</span>
                    </div>
                    <div style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(24px,3vw,38px)', lineHeight: 1.1, letterSpacing: '-0.01em' }}>{modalProj.title}</div>
                    <div style={{ fontSize: '12px', color: 'var(--muted)', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: '6px', fontWeight: 500 }}>{modalProj.company} · {modalProj.year}</div>
                  </div>
                  <button className="modal-close" onClick={closeModal}>✕</button>
                </div>
                <div className={`modal-body ${(modalProj.youtube || modalProj.gallery || modalProj.video) ? 'modal-body--media' : ''}`}>
                  {(modalProj.youtube || modalProj.gallery || modalProj.video) && (
                    <div className="modal-media-col">
                      {modalProj.video && (
                        <video src={modalProj.video} controls style={{ width: '100%', borderRadius: '4px', display: 'block' }} />
                      )}
                      {modalProj.youtube && (
                        <div style={{ position: 'relative', paddingBottom: '56.25%', height: 0 }}>
                          <iframe src={modalProj.youtube} style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', border: 0 }} allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />
                        </div>
                      )}
                      {modalProj.gallery && <Carousel images={modalProj.gallery} />}
                    </div>
                  )}
                  <div className="modal-text-col">
                    <p style={{ fontSize: '15px', color: 'rgba(245,240,234,0.75)', lineHeight: 1.7, marginBottom: '20px' }}>{modalProj.summary}</p>
                    <div style={{ fontFamily: 'var(--mono)', fontSize: '10px', letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: '12px' }}>Key Impact</div>
                    <div className="modal-impacts">
                      {modalProj.impacts.map(imp => (
                        <div key={imp} className="modal-impact-row">
                          <div className="modal-impact-icon"></div>
                          <div className="modal-impact-text" style={{ fontWeight: 600, color: 'var(--text)' }}>{imp}</div>
                        </div>
                      ))}
                    </div>
                    {modalProj.details && (
                      <>
                        <div style={{ fontFamily: 'var(--mono)', fontSize: '10px', letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: '12px', marginTop: '24px' }}>Details</div>
                        <p style={{ fontSize: '14px', color: 'var(--muted)', lineHeight: 1.7, marginBottom: '20px' }} dangerouslySetInnerHTML={{ __html: modalProj.details }} />
                      </>
                    )}
                    {modalProj.bullets && (
                      <>
                        <div style={{ fontFamily: 'var(--mono)', fontSize: '10px', letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: '12px', marginTop: '8px' }}>{modalProj.id === 'lumos-ultra' || modalProj.id === 'lumos-ebike' || modalProj.id === 'traffic-light' || modalProj.id === 'urban-combat-jackers' || modalProj.id === 'solar-camera' || modalProj.id === 'wayfar' || modalProj.id === 'filegear' || modalProj.id === 'iona-navis' ? 'Painful lessons learned' : 'Highlights'}</div>
                        <ul className="cv-bullets">
                          {modalProj.bullets.map((b, i) => <li key={i}>{b}</li>)}
                        </ul>
                      </>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
          <TweaksPanel>
            <TweakSection title="Accent Color">
              <TweakRadio id="accentColor" value={tweaks.accentColor} onChange={v => setTweak('accentColor', v)} options={['amber', 'cyan', 'rose']} />
            </TweakSection>
            <TweakSection title="Card Density">
              <TweakRadio id="cardDensity" value={tweaks.cardDensity} onChange={v => setTweak('cardDensity', v)} options={['compact', 'spacious']} />
            </TweakSection>
            <TweakSection title="Impact Bar">
              <TweakToggle id="showImpactBar" label="Show impact bar" value={tweaks.showImpactBar} onChange={v => setTweak('showImpactBar', v)} />
            </TweakSection>
          </TweaksPanel>
        </>
      );
    }

    // Render portfolio
    const pgEl = document.getElementById('portfolio-app');
    const pgRoot = ReactDOM.createRoot(pgEl);
    pgRoot.render(<PortfolioApp />);

    // Render CV timeline
    const cvEl = document.getElementById('cv-timeline');
    const cvRoot = ReactDOM.createRoot(cvEl);
    cvRoot.render(
      <>
        {JOBS.map((job, i) => <CVItem key={i} job={job} idx={i} />)}
      </>
    );

    function EducationGrid() {
      return (
        <>
          {EDUCATION.map((item) => (
            <div className="edu-card" key={item.school + '-' + item.degree}>
              <div className="edu-school">{item.school}</div>
              <div className="edu-degree">{item.degree}</div>
              <div className="edu-detail">{item.detail}</div>
            </div>
          ))}
        </>
      );
    }

    // Education
    const eduEl = document.getElementById('education-grid');
    if (eduEl) {
      const eduRoot = ReactDOM.createRoot(eduEl);
      eduRoot.render(<EducationGrid />);
    }

    // Skills
    const swEl = document.getElementById('skills-wrap');
    const swRoot = ReactDOM.createRoot(swEl);
    swRoot.render(
      <>
        {SKILLS.map(s => <span key={s} className="skill-tag">{s}</span>)}
      </>
    );

    // AI CV
    const aiCvBody = document.getElementById('ai-cv-body');
    if (aiCvBody) aiCvBody.textContent = (SITE_PROFILE.documents && SITE_PROFILE.documents.aiCv) || '';

    function BlogApp() {
      const [modalBlog, setModalBlog] = React.useState(null);
      const [blogContent, setBlogContent] = React.useState('');

      const openBlog = async (blog) => {
        setModalBlog(blog);
        try {
          const resp = await fetch(blog.file);
          const html = await resp.text();
          // Extract body content if it's a full HTML file, or just the content
          const bodyMatch = html.match(/<body[^>]*>([\s\S]*)<\/body>/i);
          setBlogContent(bodyMatch ? bodyMatch[1] : html);
        } catch (e) {
          setBlogContent('<p>Error loading blog content.</p>');
        }
      };

      const closeModal = () => { setModalBlog(null); setBlogContent(''); };

      return (
        <>
          <BlogGrid onOpen={openBlog} />

          <div className={`modal-overlay ${modalBlog ? 'open' : ''}`} onClick={(e) => { if (e.target.classList.contains('modal-overlay')) closeModal(); }}>
            {modalBlog && (
              <div className="modal modal--wide" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                  <div>
                    <div style={{ marginBottom: '10px' }}><span style={{ background: 'var(--accent)', color: 'var(--bg)', padding: '4px 10px', fontSize: '10px', fontWeight: 600, textTransform: 'uppercase', borderRadius: '2px' }}>Article</span></div>
                    <div style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(24px,3vw,38px)', lineHeight: 1.1, letterSpacing: '-0.01em' }}>{modalBlog.title}</div>
                    <div style={{ fontSize: '12px', color: 'var(--muted)', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: '6px', fontWeight: 500 }}>{modalBlog.date}</div>
                  </div>
                  <button className="modal-close" onClick={closeModal}>✕</button>
                </div>
                <div className="modal-body">
                  <div className="blog-content-wrap" dangerouslySetInnerHTML={{ __html: blogContent || '<p>Loading...</p>' }} />
                </div>
              </div>
            )}
          </div>
        </>
      );
    }

    // Render Blog
    const blogEl = document.getElementById('blog-app-mount');
    if (blogEl) {
      const blogRoot = ReactDOM.createRoot(blogEl);
      blogRoot.render(<BlogApp />);
    }
    function MarkdownRenderer({ markdown, url }) {
      const [content, setContent] = React.useState('');

      React.useEffect(() => {
        const renderMarkdown = (text) => {
          if (window.marked) {
            setContent(window.marked.parse(text));
          } else {
            setContent('<p>Error: marked.js not loaded.</p>');
          }
        };

        if (typeof markdown === 'string') {
          renderMarkdown(markdown);
          return;
        }

        fetch(url)
          .then(res => res.text())
          .then(renderMarkdown)
          .catch(() => setContent(`<p>Error loading ${url}</p>`));
      }, [markdown, url]);

      return <div dangerouslySetInnerHTML={{ __html: content }} />;
    }

    const culturalFitMount = document.getElementById('cultural-fit-mount');
    if (culturalFitMount) {
      const root = ReactDOM.createRoot(culturalFitMount);
      root.render(<MarkdownRenderer markdown={(SITE_PROFILE.documents && SITE_PROFILE.documents.culturalFit) || ''} url={(SITE_PROFILE.documents && SITE_PROFILE.documents.culturalFitUrl) || 'shared/profile/cultural-fit.md'} />);
    }

}).catch((error) => {
  console.error('Failed to initialize tabs portfolio from shared profile data:', error);
  const mount = document.getElementById('portfolio-app');
  if (mount) {
    mount.innerHTML = '<p style="color: var(--muted); padding: 24px 0;">Profile data could not be loaded.</p>';
  }
});
