// D2 v2 — Home + Projects pages

// --- Storyblok POC : contenu éditable du bandeau d'intro ---
// Valeurs par défaut = ce qui était codé en dur. Le site marche tel quel sans token.
const D2V2_HOME_INTRO_DEFAULT = {
  eyebrow: "La philosophie",
  title_accent: "Un seul regard,",
  title_rest: "du gros œuvre à l'aménagement intérieur.",
  body: "Je transforme votre maison en un lieu unique qui raconte votre histoire, sans que vous ayez à lever le petit doigt.",
};

// Reproduit storyblokEditable() du SDK : rend l'élément cliquable dans l'éditeur visuel.
function sbEditable(blok) {
  if (!blok || !blok._editable) return {};
  try {
    const opt = JSON.parse(blok._editable.replace(/^<!--#storyblok#/, "").replace(/-->$/, ""));
    return { "data-blok-c": JSON.stringify(opt), "data-blok-uid": opt.id + "-" + opt.uid };
  } catch (e) { return {}; }
}

function sbMapIntro(c) {
  c = c || {};
  return {
    eyebrow: c.eyebrow || D2V2_HOME_INTRO_DEFAULT.eyebrow,
    title_accent: c.title_accent || D2V2_HOME_INTRO_DEFAULT.title_accent,
    title_rest: c.title_rest || D2V2_HOME_INTRO_DEFAULT.title_rest,
    body: c.intro_body || D2V2_HOME_INTRO_DEFAULT.body,
  };
}

function D2V2Home({ go, openCfg }) {
  const [heroIdx, setHeroIdx] = React.useState(0);
  const projects = useStoryblokProjects(); // liste éditable (Storyblok) ou fallback codé en dur
  const [sb, setSb] = React.useState(null); // contenu Storyblok de la page Accueil (ou null)
  const T = (k, d) => (sb && sb[k] != null && sb[k] !== '' ? sb[k] : d);             // texte éditable
  const IMG = (k, d, w, h) => (sb && sb[k] && sb[k].filename ? sbImg(sb[k].filename, w, h, sb[k].focus) : d); // image éditable (asset), redimensionnée
  // Refonte « blocs de section » : chaque section = un blok Storyblok cliquable dans l'aperçu.
  // Lecture depuis le blok si présent → sinon repli sur les champs à plat (T/IMG) → sinon défaut.
  const blok = (k) => (sb && Array.isArray(sb[k]) && sb[k][0]) || null;
  const BT = (b, k, d) => (b && b[k] != null && b[k] !== '' ? b[k] : T(k, d));
  const BIMG = (b, k, d, w, h) => (b && b[k] && b[k].filename ? sbImg(b[k].filename, w, h, b[k].focus) : IMG(k, d, w, h));
  const secHero = blok('sec_hero'), secIntro = blok('sec_intro'), secMosaic = blok('sec_mosaic'), secStatement = blok('sec_statement'), secCta = blok('sec_cta');
  React.useEffect(() => {
    const t = setInterval(() => setHeroIdx(i => (i + 1) % projects.length), 5500);
    return () => clearInterval(t);
  }, [projects.length]);

  // Storyblok : charge le contenu publié/draft + branche l'édition visuelle live.
  React.useEffect(() => {
    const token = window.STORYBLOK_PREVIEW_TOKEN;
    if (!token) return; // pas de token -> garde les défauts
    const slug = window.STORYBLOK_STORY_SLUG || "home";
    const base = window.STORYBLOK_REGION === "us" ? "https://api-us.storyblok.com" : "https://api.storyblok.com";
    fetch(`${base}/v2/cdn/stories/${slug}?version=${sbVersion()}&token=${token}&cv=${Date.now()}`)
      .then(r => (r.ok ? r.json() : null))
      .then(d => { if (d && d.story && d.story.content) setSb(d.story.content); })
      .catch(() => {});

    // Bridge d'édition visuelle (le script peut charger après ce useEffect -> petit retry).
    let tries = 0;
    const initBridge = () => {
      if (window.StoryblokBridge) {
        const bridge = new window.StoryblokBridge();
        bridge.on(["input"], (e) => { if (e && e.story && e.story.content) setSb(e.story.content); });
        bridge.on(["published", "change"], () => window.location.reload());
      } else if (tries++ < 20) {
        setTimeout(initBridge, 200);
      }
    };
    initBridge();
  }, []);

  return (
    <>
      {/* HERO — slideshow + typographic overlay */}
      <section className="d2v2-hero" {...sbEditable(secHero)} style={{position:'relative', height:'100dvh', minHeight:560, overflow:'hidden'}}>
        {projects.map((p, i) => (
          <div key={p.id} style={{position:'absolute', inset:0, opacity: i === heroIdx ? 1 : 0, transition:'opacity 1.6s cubic-bezier(.4,0,.2,1)'}}>
            <img src={p.img} alt={i === heroIdx ? `${p.title} — ${p.sub}` : ''} style={{width:'100%', height:'100%', objectFit:'cover',
              filter:'saturate(1.05) contrast(1.02)',
              imageRendering:'auto',
              transform: i === heroIdx ? 'scale(1.08)' : 'scale(1.02)',
              transition:'transform 8s linear'}}/>
          </div>
        ))}
        <div style={{position:'absolute', inset:0, background:'linear-gradient(180deg, rgba(26,21,18,0.25) 0%, rgba(26,21,18,0.12) 40%, rgba(26,21,18,0.72) 100%)'}}/>
        {/* Grain overlay to hide pixelation */}
        <div style={{position:'absolute', inset:0, opacity:0.18, mixBlendMode:'overlay', pointerEvents:'none',
          backgroundImage:"url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/></filter><rect width='200' height='200' filter='url(%23n)' opacity='0.8'/></svg>\")",
          backgroundSize:'200px 200px'}}/>

        <div style={{position:'absolute', top:'clamp(90px, 12vh, 120px)', left:'clamp(24px, 4vw, 56px)', right:'clamp(24px, 4vw, 56px)', display:'flex', justifyContent:'flex-end', color:'var(--cream)'}}>
          <span style={{display:'flex', gap:6}}>
            {projects.map((_, i) => (
              <button key={i} aria-label={`Projet ${i+1}`} onClick={() => setHeroIdx(i)}
                style={{width:24, height:14, padding:0, display:'flex', alignItems:'center', background:'transparent', border:'none', cursor:'pointer'}}>
                <span style={{width:24, height:2, background: i === heroIdx ? 'var(--cream)' : 'rgba(249,240,233,0.35)', transition:'background .4s'}}/>
              </button>
            ))}
          </span>
        </div>

        <h1 style={{position:'absolute', left:'clamp(24px, 4vw, 56px)', right:'clamp(24px, 4vw, 56px)', bottom:'clamp(100px, 14vh, 180px)', margin:0, color:'var(--cream)', fontFamily:'var(--font-sans)', fontSize:'clamp(34px, 6vw, 84px)', lineHeight:0.98, letterSpacing:'-0.03em', fontWeight:500}}>
          <SplitText step={40}>{BT(secHero,'hero_title_line1','Architecte')}</SplitText><br/>
          <span style={{color:'var(--terracotta)', fontFamily:'var(--font-display)', fontStyle:'italic', fontWeight:300}}>
            <SplitText step={40} delay={200}>{BT(secHero,'hero_title_line2',"et architecte d'intérieur")}</SplitText>
          </span>
        </h1>

        <div style={{position:'absolute', left:'clamp(24px, 4vw, 56px)', right:'clamp(24px, 4vw, 56px)', bottom:32, display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:20, color:'var(--cream)', flexWrap:'wrap'}}>
          <div style={{fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase'}}>
            <div style={{opacity:.7, marginBottom:4}}>{BT(secHero,'hero_label_current','En ce moment ·')}</div>
            <button onClick={() => go('project:'+projects[heroIdx].id)} data-cursor="Voir" style={{color:'var(--cream)', fontSize:14, textTransform:'none', letterSpacing:0, fontFamily:'var(--font-display)', fontWeight:400}}>
              {projects[heroIdx].title} — {projects[heroIdx].sub}
            </button>
          </div>
          <div style={{fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase', display:'flex', alignItems:'center', gap:12, opacity:.9}}>
            <span style={{width:40, height:1, background:'var(--cream)'}}/> {BT(secHero,'hero_scroll_cta','Défiler')}
          </div>
        </div>
      </section>

      {/* INTRO BAND — manifeste rapide avec arche animée (éditable Storyblok) */}
      <section {...sbEditable(secIntro)} style={{padding:'clamp(64px, 10vw, 120px) clamp(24px, 4vw, 56px)', borderBottom:'1px solid var(--line)', display:'grid', gridTemplateColumns:'1fr 2fr', gap:'clamp(32px, 5vw, 80px)', alignItems:'start'}}>
        <div aria-hidden="true"/>
        <Reveal delay={150}>
          <Eyebrow style={{marginBottom:24}}>{BT(secIntro,'eyebrow','La philosophie')}</Eyebrow>
          <p style={{fontFamily:'var(--font-display)', fontSize:'clamp(24px, 3.8vw, 46px)', lineHeight:1.22, fontWeight:300, letterSpacing:'-0.015em', margin:0}}>
            <em style={{fontStyle:'italic', color:'var(--terracotta)'}}>{BT(secIntro,'title_accent','Un seul regard,')}</em><br/>
            {BT(secIntro,'title_rest',"du gros œuvre à l'aménagement intérieur.")}
          </p>
          <p style={{fontFamily:'var(--font-display)', fontSize:'clamp(17px, 2vw, 24px)', lineHeight:1.4, fontWeight:300, color:'var(--ink-soft)', margin:'24px 0 0', maxWidth:680}}>
            {BT(secIntro,'intro_body','Je transforme votre maison en un lieu unique qui raconte votre histoire, sans que vous ayez à lever le petit doigt.')}
          </p>
        </Reveal>
      </section>

      {/* MOSAIC — visual rythm */}
      <section {...sbEditable(secMosaic)} style={{background:'var(--cream)'}}>
        <div className="d2v2-mosaic" style={{display:'grid', gridTemplateColumns:'2fr 1fr 1fr', gridTemplateRows:'300px 300px', gap:0}}>
          <ImageReveal src={BIMG(secMosaic,'mosaic_img_main', D2V2_IMG.arche, 1600, 1230)} style={{gridRow:'1 / 3', height:'100%'}} delay={0}/>
          <ImageReveal src={BIMG(secMosaic,'mosaic_img_2', D2V2_IMG.vases, 900, 690)} style={{height:'100%'}} delay={120}/>
          <div style={{background:'var(--terracotta)', color:'var(--cream)', padding:28, display:'flex', flexDirection:'column', justifyContent:'space-between'}}>
            <Eyebrow color="var(--cream)" style={{opacity:.9}}>{BT(secMosaic,'mosaic_eyebrow','En bref')}</Eyebrow>
            <div style={{fontFamily:'var(--font-display)', fontSize:40, fontWeight:300, fontStyle:'italic', lineHeight:0.95, letterSpacing:'-0.02em'}}>{BT(secMosaic,'mosaic_stat_number','10 ans')}<br/>{BT(secMosaic,'mosaic_stat_label',"d'expérience")}</div>
            <div style={{fontFamily:'var(--font-mono)', fontSize:10, opacity:.85, lineHeight:1.7}}>{BT(secMosaic,'mosaic_bio_name','Mathilde Lazzari')}<br/>{BT(secMosaic,'mosaic_bio_since','depuis 2021')}<br/>{BT(secMosaic,'mosaic_bio_projects','15 projets')}</div>
          </div>
          <ImageReveal src={BIMG(secMosaic,'mosaic_img_3', D2V2_IMG.moodboard, 900, 690)} style={{height:'100%'}} delay={240}/>
          <ImageReveal src={BIMG(secMosaic,'mosaic_img_4', D2V2_IMG.portrait, 900, 690)} style={{height:'100%'}} delay={360}/>
        </div>
      </section>

      {/* STATEMENT ORANGE */}
      <section {...sbEditable(secStatement)} style={{background:'var(--terracotta)', color:'var(--cream)', padding:'160px 56px', position:'relative', overflow:'hidden'}}>
        <Reveal>
          <Eyebrow color="var(--cream)" style={{opacity:.85, marginBottom:40}}>{BT(secStatement,'statement_eyebrow','Conviction')}</Eyebrow>
          <p style={{fontFamily:'var(--font-display)', fontSize:76, fontWeight:300, lineHeight:1.1, letterSpacing:'-0.025em', margin:0, maxWidth:1400}}>
            {BT(secStatement,'statement_quote_line1',"« Un bâtiment ancien n'est pas un problème à résoudre.")}<br/>
            <em style={{fontStyle:'italic', color:'var(--cream)'}}>{BT(secStatement,'statement_quote_line2',"C'est une phrase à prolonger. »")}</em>
          </p>
          <div style={{fontFamily:'var(--font-mono)', fontSize:12, marginTop:48, opacity:.8}}>{BT(secStatement,'statement_signature','— M. Lazzari')}</div>
        </Reveal>
      </section>

      {/* CONFIGURATOR CTA — signature element */}
      <section {...sbEditable(secCta)} style={{padding:'140px 56px 120px', background:'var(--cream-deep)'}}>
        <div style={{display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:80, alignItems:'center'}}>
          <Reveal>
            <Eyebrow style={{marginBottom:24}}>{BT(secCta,'cta_eyebrow','Votre projet')}</Eyebrow>
            <h2 style={{fontFamily:'var(--font-sans)', color:'var(--ink)', fontSize:96, fontWeight:500, letterSpacing:'-0.04em', margin:0, lineHeight:0.92}}>
              {BT(secCta,'cta_title_line1','Parlons')}<br/>{BT(secCta,'cta_title_line2','de votre')}<br/><em style={{fontFamily:'var(--font-display)', fontStyle:'italic', color:'var(--terracotta)', fontWeight:300}}>{BT(secCta,'cta_title_line3','projet')}</em>.
            </h2>
            <p style={{fontSize:17, lineHeight:1.6, color:'var(--ink-soft)', marginTop:32, maxWidth:500, fontWeight:300}}>
              {BT(secCta,'cta_subtitle','Cinq questions simples pour vous répondre avec justesse. Comptez 2 minutes. Vous recevez en retour une première estimation chiffrée et un rendez-vous proposé.')}
            </p>
            <button onClick={openCfg} data-cursor="Commencer" style={{
              marginTop:40, padding:'22px 40px', background:'var(--terracotta)', color:'var(--cream)',
              borderRadius:999, fontSize:15, letterSpacing:'0.05em',
              display:'inline-flex', alignItems:'center', gap:16, transition:'transform .3s'
            }}>
              <span>{BT(secCta,'cta_button_label','Lancer le questionnaire')}</span>
              <span style={{width:28, height:28, borderRadius:999, background:'var(--ink)', color:'var(--cream)', display:'flex', alignItems:'center', justifyContent:'center'}}>→</span>
            </button>
          </Reveal>
          <Reveal delay={150}>
            <div style={{display:'flex', flexDirection:'column'}}>
              {[[BT(secCta,'cta_feature_1_title','2 minutes chrono'), BT(secCta,'cta_feature_1_sub',"Le temps d'un café")],
                [BT(secCta,'cta_feature_2_title','Sans engagement'), BT(secCta,'cta_feature_2_sub','Aucune obligation')],
                [BT(secCta,'cta_feature_3_title','Réponse sous 72h'), BT(secCta,'cta_feature_3_sub','Jours ouvrés')]].map(([t, s]) => (
                <div key={t} style={{display:'flex', alignItems:'flex-start', gap:18, padding:'26px 0', borderTop:'1px solid var(--line)'}}>
                  <span style={{marginTop:4, flexShrink:0}}><Arch size={18} color="var(--terracotta)" thickness={2}/></span>
                  <div>
                    <div style={{fontFamily:'var(--font-display)', fontSize:24, fontWeight:400, letterSpacing:'-0.01em', lineHeight:1.1}}>{t}</div>
                    <div style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--stone)', marginTop:6, letterSpacing:'0.06em', textTransform:'uppercase'}}>{s}</div>
                  </div>
                </div>
              ))}
              <div style={{borderTop:'1px solid var(--line)'}}/>
            </div>
          </Reveal>
        </div>
      </section>
    </>
  );
}

function D2V2Projects({ go }) {
  const [typeF, setTypeF] = React.useState('Tous');
  const [statusF, setStatusF] = React.useState('Tous');
  const [hovered, setHovered] = React.useState(null);
  const projects = useStoryblokProjects();
  const { T: C } = useStoryblokStory('config'); // micro-textes globaux (entrée « Configuration »)

  const types = ['Tous', 'Nouvelle construction', 'Rénovation', 'Transformation', 'Extension'];
  const statuses = [['Tous', C('filter_all', 'Tous')], ['en-cours', C('status_in_progress', 'En cours')], ['livre', C('status_done', 'Livré')]];

  const byStatus = statusF === 'Tous' ? projects : projects.filter(p => p.status === statusF);
  const filtered = typeF === 'Tous' ? byStatus : byStatus.filter(p => p.type === typeF);
  const countType = (t) => (t === 'Tous' ? byStatus.length : byStatus.filter(p => p.type === t).length);

  return (
    <section style={{padding:'80px 56px 120px'}}>
      <Reveal>
        <Eyebrow>{C('projects_eyebrow', 'Projets')}</Eyebrow>
        <h2 style={{fontFamily:'var(--font-sans)', color:'var(--ink)', fontSize:'clamp(30px, 4vw, 56px)', fontWeight:500, letterSpacing:'-0.03em', margin:'20px 0 0', lineHeight:1}}>
          {C('projects_heading', 'Projets de')} <em style={{fontFamily:'var(--font-display)', fontStyle:'italic', color:'var(--terracotta)', fontWeight:300}}>{C('projects_heading_accent', 'transformation')}</em>.
        </h2>
      </Reveal>

      {/* Filters — TYPE chips + STATUT toggle */}
      <div className="d2v2-proj-filters" style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:32, flexWrap:'wrap', marginTop:48, marginBottom:24}}>
        <div style={{display:'flex', gap:10, flexWrap:'wrap'}}>
          {types.map(t => (
            <button key={t} onClick={() => setTypeF(t)} data-cursor="Filtrer"
              style={{padding:'10px 20px', border:'1px solid var(--ink)', borderRadius:999,
                background: typeF === t ? 'var(--ink)' : 'transparent',
                color: typeF === t ? 'var(--cream)' : 'var(--ink)', fontSize:13, transition:'all .2s'}}>
              {t} <span style={{opacity:.6, marginLeft:4}}>{countType(t)}</span>
            </button>
          ))}
        </div>
        <div style={{display:'flex', alignItems:'center', gap:14}}>
          <span style={{fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.12em', color:'var(--stone)', textTransform:'uppercase'}}>{C('label_status', 'Statut')}</span>
          <div style={{display:'inline-flex', border:'1px solid var(--ink)', borderRadius:999, overflow:'hidden'}}>
            {statuses.map(([val, label], i) => (
              <button key={val} onClick={() => setStatusF(val)} data-cursor="Filtrer"
                style={{padding:'9px 16px', border:'none', borderLeft: i === 0 ? 'none' : '1px solid var(--line)',
                  background: statusF === val ? 'var(--terracotta)' : 'transparent',
                  color: statusF === val ? 'var(--cream)' : 'var(--ink)', fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.04em', transition:'all .2s'}}>
                {label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* One project per line — image always visible */}
      {filtered.length === 0 ? (
        <div style={{padding:'80px 0', fontFamily:'var(--font-display)', fontStyle:'italic', fontSize:24, color:'var(--stone)'}}>{C('label_no_projects', 'Aucun projet pour cette sélection.')}</div>
      ) : (
        <div style={{marginTop:8}}>
          {filtered.map((p) => {
            const lieu = (p.sub.split('—')[1] || p.sub).trim();
            return (
              <Reveal as="button" key={p.id} delay={40}
                onClick={() => go('project:'+p.id)} onMouseEnter={() => setHovered(p.id)} onMouseLeave={() => setHovered(null)} data-cursor="Voir"
                className="d2v2-projline"
                style={{display:'grid', gridTemplateColumns:'minmax(0, 1.05fr) minmax(0, 1fr)', gap:'clamp(28px, 4vw, 72px)', alignItems:'center', padding:'clamp(24px, 3vw, 44px) 0', borderTop:'1px solid var(--line)', width:'100%', textAlign:'left', background:'none'}}>
                <div style={{position:'relative', overflow:'hidden', aspectRatio:'3 / 2', background:'var(--cream-deep)'}}>
                  <img src={p.img} alt={p.title} loading="lazy" style={{position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', transform: hovered === p.id ? 'scale(1.05)' : 'scale(1)', transition:'transform 1.2s cubic-bezier(.2,.7,.2,1)'}}/>
                  {p.status === 'en-cours' && (
                    <span style={{position:'absolute', top:16, left:16, fontFamily:'var(--font-mono)', fontSize:9, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--cream)', background:'rgba(26,21,18,0.5)', padding:'6px 11px'}}>{C('status_in_progress', 'En cours')}</span>
                  )}
                </div>
                <div style={{minWidth:0}}>
                  <div style={{display:'flex', alignItems:'baseline', gap:'clamp(14px, 1.6vw, 28px)'}}>
                    <span style={{fontFamily:'var(--font-display)', fontStyle:'italic', fontWeight:300, color:'var(--terracotta)', fontSize:'clamp(26px, 3vw, 48px)', lineHeight:0.8, flexShrink:0}}>{p.num}</span>
                    <h3 style={{fontFamily:'var(--font-sans)', fontSize:'clamp(28px, 3.6vw, 56px)', fontWeight:500, letterSpacing:'-0.03em', lineHeight:1, margin:0, color: hovered === p.id ? 'var(--terracotta)' : 'var(--ink)', transition:'color .3s'}}>{p.title}</h3>
                  </div>
                  <div style={{fontFamily:'var(--font-display)', fontSize:17, fontStyle:'italic', fontWeight:300, color:'var(--stone)', marginTop:16}}>{lieu}</div>
                  <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', gap:16, marginTop:24, paddingTop:14, borderTop:'1px solid var(--line)', fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--stone)'}}>
                    <span>{p.type} · {p.year}</span>
                    <span style={{display:'inline-flex', alignItems:'center', gap:8, color: hovered === p.id ? 'var(--terracotta)' : 'var(--ink)', transition:'color .3s'}}>
                      Voir le projet <span style={{display:'inline-block', transition:'transform .3s', transform: hovered === p.id ? 'translateX(5px)' : 'none'}}>→</span>
                    </span>
                  </div>
                </div>
              </Reveal>
            );
          })}
          <div style={{borderTop:'1px solid var(--line)'}}/>
        </div>
      )}
    </section>
  );
}

window.D2V2Home = D2V2Home;
window.D2V2Projects = D2V2Projects;
