// D2 v2 — shared utilities: reveal hook, cursor, arch SVG, shared data

const D2V2_IMG = {
  portrait: 'd2v2/img/6-portrait.jpg',
  salon: 'd2v2/img/2-canape.jpg',
  arche: 'd2v2/img/5-salle-manger.jpg',
  vases: 'd2v2/img/1-cuisine.jpg',
  moodboard: 'd2v2/img/7-plantes.jpg',
  cuisine: 'd2v2/img/1-cuisine.jpg',
  planTravail: 'd2v2/img/3-plan-travail.jpg',
  banc: 'd2v2/img/4-banc.jpg',
};

// status: 'livre' (terminé) | 'en-cours' (chantier ou étude en cours)
// type: 'Nouvelle construction' | 'Rénovation' | 'Transformation' | 'Extension'
const gallery = (id, n) => Array.from({ length: n }, (_, i) => `d2v2/img/projets/${id}/p-${String(i + 1).padStart(2, '0')}.jpg`);
const D2V2_PROJECTS = [
  { id: 'notre-maison', num: '01', title: 'Notre maison', sub: 'Maison familiale — Belgique', year: '2024', type: 'Transformation', status: 'livre', surface: '—', rooms: '—', img: 'd2v2/img/projets/notre-maison/p-01.jpg', gallery: gallery('notre-maison', 24), excerpt: "Transformation complète d'une maison familiale, repensée pièce par pièce autour de la lumière et des usages du quotidien.", color: '#c9784a' },
  { id: 'extension-sabine', num: '02', title: 'Extension de Sabine', sub: 'Extension — Belgique', year: '2024', type: 'Extension', status: 'livre', surface: '—', rooms: '—', img: 'd2v2/img/projets/extension-sabine/p-01.jpg', gallery: gallery('extension-sabine', 27), excerpt: "Extension contemporaine prolongeant la maison existante, en dialogue avec le jardin et la lumière.", color: '#de5023' },
  { id: 'wellness-belle', num: '03', title: "Wellness B'elle", sub: 'Espace bien-être — Belgique', year: '2025', type: 'Transformation', status: 'en-cours', surface: '—', rooms: '—', img: 'd2v2/img/projets/wellness-belle/p-01.jpg', gallery: gallery('wellness-belle', 2), excerpt: "Aménagement d'un espace bien-être : un lieu apaisant, sensoriel et sur mesure. Projet en cours.", color: '#9a5a2e' },
  { id: 'marie-tom', num: '04', title: 'Extension de Marie & Tom', sub: 'Extension — Belgique', year: '2025', type: 'Extension', status: 'en-cours', surface: '—', rooms: '—', img: 'd2v2/img/projets/marie-tom/p-01.jpg', gallery: gallery('marie-tom', 9), excerpt: "Extension d'une maison pour gagner en espace de vie et en lumière. Projet en cours.", color: '#b8643a' },
  { id: 'celine-stephane', num: '05', title: 'Extension de Céline & Stéphane', sub: 'Extension — Belgique', year: '2026', type: 'Extension', status: 'en-cours', surface: '—', rooms: '—', img: 'd2v2/img/projets/celine-stephane/p-01.jpg', gallery: gallery('celine-stephane', 11), excerpt: "Extension repensant le rapport entre intérieur et extérieur de la maison. Projet en cours.", color: '#d8793d' },
];

// Détecte si on est dans l'éditeur visuel Storyblok (iframe ou param _storyblok).
// En éditeur → on lit le brouillon (draft) ; sur le site live → le contenu publié.
function sbInEditor() {
  try {
    return (window.location.search.indexOf('_storyblok') !== -1) || (window.self !== window.top);
  } catch (e) { return true; }
}
function sbVersion() { return sbInEditor() ? 'draft' : 'published'; }

// ── Formulaires (questionnaire + contact) → /api/contact → e-mail à Mathilde.
// Résout { ok: true } ou rejette ; jamais de « succès » affiché si l'envoi a échoué.
function d2v2SendForm(payload) {
  return fetch('/api/contact', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  }).then(r => r.json().catch(() => ({})).then(j => {
    if (!r.ok || !j.ok) throw new Error(j.error || ('http ' + r.status));
    return j;
  }));
}

// Champ piège anti-robots : invisible pour les humains, rempli par les robots.
function D2V2Honeypot({ value, onChange }) {
  return (
    <div aria-hidden="true" style={{position:'absolute', left:-10000, top:'auto', width:1, height:1, overflow:'hidden'}}>
      <label>Site web <input type="text" name="website" tabIndex={-1} autoComplete="off" value={value} onChange={e => onChange(e.target.value)}/></label>
    </div>
  );
}

// ── Images Storyblok : servies via le service d'images (redimension + WebP) au lieu
// du fichier brut. Les photos importées pèsent souvent 4 à 14 Mo ; ramenées à la largeur
// utile elles restent nettes et chargent vite. Si un point focal a été réglé dans Storyblok
// et qu'une hauteur est demandée, le recadrage se fait autour de ce point.
// Les chemins locaux, les SVG et les URLs déjà transformées passent tels quels.
function sbImg(url, w = 2000, h = 0, focus = '') {
  if (!url || typeof url !== 'string' || url.indexOf('a.storyblok.com/f/') === -1 || /\.svg$/i.test(url) || url.indexOf('/m/') !== -1) return url;
  const filters = ['format(webp)', 'quality(82)'];
  if (h && focus) filters.push(`focal(${focus})`);
  return `${url}/m/${w}x${h && focus ? h : 0}/filters:${filters.join(':')}`;
}

// ── Mise en forme légère dans les champs texte Storyblok (récits, titres) :
//   **gras**   *italique*   ==orange italique==
// Sans marqueur, le texte s'affiche tel quel (rétro-compatible avec le contenu existant).
const SB_RICH_RE = /(==[^=]+==|\*\*[^*]+\*\*|\*[^*\s][^*]*\*)/g;
function sbRich(text) {
  const s = String(text == null ? '' : text);
  if (s.indexOf('==') === -1 && s.indexOf('*') === -1) return s;
  return s.split(SB_RICH_RE).filter(part => part !== '').map((part, i) => {
    if (part.length > 4 && part.startsWith('==') && part.endsWith('==')) return <em key={i} style={{fontFamily:'var(--font-display)', fontStyle:'italic', fontWeight:300, color:'var(--terracotta)'}}>{sbRich(part.slice(2, -2))}</em>;
    if (part.length > 4 && part.startsWith('**') && part.endsWith('**')) return <strong key={i} style={{fontWeight:600, color:'var(--ink)'}}>{part.slice(2, -2)}</strong>;
    if (part.length > 2 && part.startsWith('*') && part.endsWith('*')) return <em key={i} style={{fontStyle:'italic'}}>{part.slice(1, -1)}</em>;
    return part;
  });
}
function sbPlain(text) { return String(text == null ? '' : text).replace(/==|\*\*|\*/g, ''); }

// ── Storyblok — charge une story éditable + branche l'édition visuelle live.
// Retourne { sb, T, IMG } : T(clé, défaut) pour le texte, IMG(clé, défaut) pour une image (asset).
// Sans token configuré, sb reste null → tout retombe sur les valeurs par défaut (le site marche tel quel).
function useStoryblokStory(slug) {
  const [sb, setSb] = React.useState(null);
  React.useEffect(() => {
    const token = window.STORYBLOK_PREVIEW_TOKEN;
    if (!token) return undefined;
    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(() => {});
    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 undefined;
  }, [slug]);
  const T = (k, d) => (sb && sb[k] != null && sb[k] !== '' ? sb[k] : d);
  const IMG = (k, d, w, h) => (sb && sb[k] && sb[k].filename ? sbImg(sb[k].filename, w, h, sb[k].focus) : d);
  return { sb, T, IMG };
}

// ── Storyblok — liste des projets éditables (dossier projets/). Fallback : D2V2_PROJECTS codé en dur.
// Lit une couleur qu'elle vienne d'un champ texte (« #de5023 ») OU d'un
// sélecteur de couleur visuel (objet { color: '#…' }). Tolérant → basculer un
// champ couleur vers le plugin « native color picker » ne casse pas le rendu.
function sbColor(v, fallback) {
  if (!v) return fallback;
  if (typeof v === 'object') return v.color || v.value || fallback;
  return v;
}

function sbMapProject(story) {
  const c = story.content || {};
  const slug = (story.slug || '').split('/').pop();
  const gallery = Array.isArray(c.gallery) ? c.gallery.map(a => a && a.filename && sbImg(a.filename, 1600)).filter(Boolean) : null;
  const mats = [];
  for (let i = 1; i <= 8; i++) {
    if (c['material_' + i + '_name']) {
      const mimg = c['material_' + i + '_image'];
      mats.push([c['material_' + i + '_name'], sbColor(c['material_' + i + '_color'], '#cccccc'), c['material_' + i + '_use'] || '', (mimg && mimg.filename) || '']);
    }
  }
  // Récit : un seul champ texte (paragraphes séparés par un saut de ligne) si présent,
  // sinon repli sur les anciens champs numérotés recit_p1..p4 (rétro-compatible).
  const recitP = (c.recit && String(c.recit).trim())
    ? String(c.recit).split(/\r?\n+/).map(s => s.trim()).filter(Boolean)
    : [c.recit_p1, c.recit_p2, c.recit_p3, c.recit_p4].filter(Boolean);
  return {
    // title : texte brut (listes, alt, projet suivant) ; titleRich : avec marqueurs de mise en forme.
    id: slug, num: c.num || '', title: sbPlain(c.title || ''), titleRich: c.title || '', sub: c.sub || '', year: c.year || '',
    type: c.type || '', status: c.status || 'livre', surface: c.surface || '—', rooms: c.rooms || '—',
    color: sbColor(c.color, '#c9784a'), excerpt: c.excerpt || '',
    img: (c.cover && c.cover.filename) ? sbImg(c.cover.filename, 2400) : null,
    gallery: (gallery && gallery.length) ? gallery : null,
    recit: { quote: c.recit_quote || '', p: recitP },
    materials: mats.length ? mats : null,
  };
}
function useStoryblokProjects() {
  const [list, setList] = React.useState(null);
  React.useEffect(() => {
    const token = window.STORYBLOK_PREVIEW_TOKEN;
    if (!token) return undefined;
    const base = window.STORYBLOK_REGION === 'us' ? 'https://api-us.storyblok.com' : 'https://api.storyblok.com';
    fetch(`${base}/v2/cdn/stories?starts_with=projets/&version=${sbVersion()}&per_page=100&token=${token}&cv=${Date.now()}`)
      .then(r => (r.ok ? r.json() : null))
      .then(d => {
        if (d && d.stories && d.stories.length) {
          setList(d.stories.map(sbMapProject).sort((a, b) => String(a.num).localeCompare(String(b.num))));
        }
      })
      .catch(() => {});
    let tries = 0;
    const initBridge = () => {
      if (window.StoryblokBridge) {
        const b = new window.StoryblokBridge();
        b.on(['published', 'change'], () => window.location.reload());
      } else if (tries++ < 20) { setTimeout(initBridge, 200); }
    };
    initBridge();
    return undefined;
  }, []);
  return list || window.D2V2_PROJECTS;
}

// Reproduit storyblokEditable() du SDK : rend un bloc cliquable dans l'éditeur visuel.
function sbEditableAttr(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 {}; }
}

// ── Reveal hook — triggers fade/slide on scroll into view
function useReveal() {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current || shown) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { setShown(true); io.disconnect(); }});
    }, { threshold: 0.12, rootMargin: '0px 0px -80px 0px' });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [shown]);
  return [ref, shown];
}

function Reveal({ children, delay = 0, y = 28, as: Tag = 'div', style = {}, ...rest }) {
  const [ref, shown] = useReveal();
  return (
    <Tag ref={ref} style={{
      ...style,
      opacity: shown ? 1 : 0,
      transform: `translateY(${shown ? 0 : y}px)`,
      transition: `opacity .9s cubic-bezier(.2,.7,.2,1) ${delay}ms, transform .9s cubic-bezier(.2,.7,.2,1) ${delay}ms`,
    }} {...rest}>{children}</Tag>
  );
}

// ── Parallax — gentle scroll-linked translate on an element (respects reduced motion)
function useParallax(strength = 0.06) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return undefined;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return undefined;
    let raf = 0;
    const update = () => {
      raf = 0;
      const r = el.getBoundingClientRect();
      const center = r.top + r.height / 2 - window.innerHeight / 2;
      el.style.transform = `translate3d(0, ${(-center * strength).toFixed(1)}px, 0)`;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [strength]);
  return ref;
}

// ── Custom cursor — dot that becomes label on interactives
// Disabled on touch/coarse-pointer devices (no hover).
function CustomCursor() {
  const isTouch = typeof window !== 'undefined' && (
    window.matchMedia('(hover: none)').matches ||
    window.matchMedia('(pointer: coarse)').matches
  );
  const cur = React.useRef(null);
  const [label, setLabel] = React.useState('');
  const [hover, setHover] = React.useState(false);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    if (isTouch) return;
    const onMove = (e) => {
      if (!cur.current) return;
      cur.current.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
      setVisible(true);
    };
    const onLeave = () => setVisible(false);
    const onOver = (e) => {
      const t = e.target.closest('[data-cursor]');
      if (t) { setLabel(t.getAttribute('data-cursor')); setHover(true); }
      else { setHover(false); setLabel(''); }
    };
    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseleave', onLeave);
    document.addEventListener('mouseover', onOver);
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseleave', onLeave);
      document.removeEventListener('mouseover', onOver);
    };
  }, [isTouch]);

  if (isTouch) return null;

  return (
    <div ref={cur} style={{
      position:'fixed', pointerEvents:'none', zIndex:999, top:0, left:0,
      width: hover ? 88 : 10, height: hover ? 88 : 10,
      marginLeft: hover ? -44 : -5, marginTop: hover ? -44 : -5,
      borderRadius:999, background: hover ? 'var(--terracotta)' : 'var(--ink)',
      color:'var(--cream)', display:'flex', alignItems:'center', justifyContent:'center',
      fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.06em', textTransform:'uppercase',
      opacity: visible ? 1 : 0,
      transition:'width .3s cubic-bezier(.2,.7,.2,1),height .3s cubic-bezier(.2,.7,.2,1),margin .3s cubic-bezier(.2,.7,.2,1),background .2s,opacity .2s',
      mixBlendMode: hover ? 'normal' : 'difference'
    }}>{hover ? label : ''}</div>
  );
}

// ── Arch SVG
// ── Filet fin — remplace l'arche d'origine (motif trop proche du logo du bureau
// Uman Architecture, demande de la cliente 10/2026). Même API : size = longueur.
function Arch({ size = 64, color = 'currentColor', thickness = 2 }) {
  const h = Math.max(thickness, 2);
  return (
    <svg width={size} height={h} viewBox={`0 0 ${size} ${h}`} fill="none" style={{display:'block'}}>
      <line x1="0" y1={Math.max(thickness, 2) / 2} x2={size} y2={Math.max(thickness, 2) / 2}
        stroke={color} strokeWidth={thickness}/>
    </svg>
  );
}

// ── Eyebrow — small arch mark + label (replaces the old "§" prefix)
function Eyebrow({ children, color = 'var(--terracotta)', style = {} }) {
  return (
    <div style={{display:'inline-flex', alignItems:'center', gap:9, fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.15em', color, textTransform:'uppercase', ...style}}>
      <Arch size={10} color={color} thickness={2}/>
      <span>{children}</span>
    </div>
  );
}

// ── Mathilde Lazzari brand mark — double arch "M" (filled outer + line inner)
function MLMark({ size = 40, color = 'var(--terracotta)', thin }) {
  // viewBox 100x92 — two wide outer arch strokes (M shape) + thin inner arch
  const stroke = thin || color;
  return (
    <svg width={size} height={size * 0.92} viewBox="0 0 100 92" fill="none" style={{display:'block'}}>
      {/* Left filled arch */}
      <path d="M8 92 V32 a22 22 0 0 1 44 0 V92 H38 V32 a8 8 0 0 0 -16 0 V92 Z" fill={color}/>
      {/* Right filled arch */}
      <path d="M48 92 V32 a22 22 0 0 1 44 0 V92 H78 V32 a8 8 0 0 0 -16 0 V92 Z" fill={color}/>
      {/* Inner thin arch (between the two) */}
      <path d="M42 92 V36 a8 8 0 0 1 16 0 V92" stroke={stroke} strokeWidth={1} fill="none"/>
    </svg>
  );
}

// ── Full lockup
function MLLockup({ size = 44, color = 'var(--terracotta)' }) {
  return (
    <div style={{display:'flex', flexDirection:'column', alignItems:'center', gap:10}}>
      <MLMark size={size} color={color}/>
      <div style={{fontFamily:'var(--font-sans)', fontWeight:600, fontSize:size*0.22, letterSpacing:'0.18em', color}}>MATHILDE LAZZARI</div>
      <div style={{fontFamily:'var(--font-sans)', fontWeight:400, fontSize:size*0.15, letterSpacing:'0.28em', color, opacity:.9, marginTop:-4}}>ARCHITECTE TRANSFORMATION</div>
    </div>
  );
}

// ── Animated arch — draws on scroll-in
// Filet qui se trace à l'apparition (remplace l'arche animée).
function ArchDraw({ size = 120, color = 'var(--terracotta)', thickness = 2, delay = 0 }) {
  const [ref, shown] = useReveal();
  const h = Math.max(thickness, 2);
  return (
    <svg ref={ref} width={size} height={h} viewBox={`0 0 ${size} ${h}`} fill="none" style={{display:'block'}}>
      <line x1="0" y1={h / 2} x2={size} y2={h / 2} stroke={color} strokeWidth={thickness}
        strokeDasharray={size} strokeDashoffset={shown ? 0 : size}
        style={{ transition: `stroke-dashoffset 1.2s cubic-bezier(.4,.0,.2,1) ${delay}ms` }}/>
    </svg>
  );
}

function ArchDrawLegacy({ size = 120, color = 'var(--terracotta)', thickness = 2, delay = 0 }) {
  const [ref, shown] = useReveal();
  const L = 140;
  return (
    <svg ref={ref} width={size} height={size * 56 / 48} viewBox="0 0 48 56" fill="none" style={{display:'block'}}>
      <path d="M4 56 V24 A20 20 0 0 1 44 24 V56" stroke={color} strokeWidth={thickness} fill="none"
        strokeDasharray={L} strokeDashoffset={shown ? 0 : L}
        style={{ transition: `stroke-dashoffset 1.8s cubic-bezier(.4,.0,.2,1) ${delay}ms` }}/>
    </svg>
  );
}

// ── Animated double arch — two curves echoing the logo, draws on scroll-in
// Conservé pour compatibilité : rend désormais le même filet que ArchDraw.
function ArchDrawDouble(props) { return <ArchDraw {...props}/>; }

function ArchDrawDoubleLegacy({ size = 120, color = 'var(--terracotta)', thickness = 2, delay = 0 }) {
  const [ref, shown] = useReveal();
  const L = 150;
  return (
    <svg ref={ref} width={size} height={size * 56 / 92} viewBox="0 0 92 56" fill="none" style={{display:'block'}}>
      <path d="M4 56 V24 A20 20 0 0 1 44 24 V56" stroke={color} strokeWidth={thickness} fill="none"
        strokeDasharray={L} strokeDashoffset={shown ? 0 : L}
        style={{ transition: `stroke-dashoffset 1.8s cubic-bezier(.4,.0,.2,1) ${delay}ms` }}/>
      <path d="M48 56 V24 A20 20 0 0 1 88 24 V56" stroke={color} strokeWidth={thickness} fill="none"
        strokeDasharray={L} strokeDashoffset={shown ? 0 : L}
        style={{ transition: `stroke-dashoffset 1.8s cubic-bezier(.4,.0,.2,1) ${delay + 260}ms` }}/>
    </svg>
  );
}

// ── Split text — word-by-word reveal
function SplitText({ children, delay = 0, step = 40, style = {} }) {
  const [ref, shown] = useReveal();
  const words = String(children).split(' ');
  return (
    <span ref={ref} style={{display:'inline', ...style}}>
      {words.map((w, i) => (
        <span key={i} style={{display:'inline-block', overflow:'hidden', verticalAlign:'baseline', paddingBottom:'0.32em', marginBottom:'-0.32em', paddingTop:'0.2em', marginTop:'-0.2em', paddingInline:'0.08em', marginInline:'-0.08em'}}>
          <span style={{
            display:'inline-block',
            transform: shown ? 'translateY(0)' : 'translateY(110%)',
            transition: `transform .9s cubic-bezier(.2,.7,.2,1) ${delay + i * step}ms`,
          }}>{w}{i < words.length - 1 ? '\u00A0' : ''}</span>
        </span>
      ))}
    </span>
  );
}

// ── Image reveal — mask slides up
function ImageReveal({ src, alt = '', style = {}, delay = 0 }) {
  const [ref, shown] = useReveal();
  return (
    <div ref={ref} style={{position:'relative', overflow:'hidden', ...style}}>
      <img src={src} alt={alt} style={{
        width:'100%', height:'100%', objectFit:'cover', display:'block',
        transform: shown ? 'scale(1)' : 'scale(1.08)',
        transition: `transform 1.4s cubic-bezier(.2,.7,.2,1) ${delay}ms`,
      }}/>
      <div style={{
        position:'absolute', inset:0, background:'var(--cream)',
        transform: shown ? 'translateY(-101%)' : 'translateY(0)',
        transition: `transform 1.1s cubic-bezier(.76,0,.24,1) ${delay}ms`,
      }}/>
    </div>
  );
}

Object.assign(window, { D2V2_IMG, D2V2_PROJECTS, useStoryblokStory, useStoryblokProjects, sbInEditor, sbVersion, d2v2SendForm, D2V2Honeypot, sbEditableAttr, sbImg, sbRich, sbPlain, useReveal, useParallax, Reveal, CustomCursor, Arch, ArchDraw, ArchDrawDouble, MLMark, MLLockup, SplitText, ImageReveal, Eyebrow });
