'use client';

import Image from 'next/image';
import { ArrowUpRight } from 'lucide-react';
import { useEffect, useId, useRef } from 'react';
import { site } from '@/data/site';
import styles from './author-chapter.module.css';

const biography = site.bio;

function BrandSeal({ id }: { id: string }) {
  const pathId = `${id}-author-seal`;

  return <svg className={styles.seal} viewBox="0 0 120 120" aria-hidden="true" focusable="false">
    <defs>
      <path id={pathId} d="M 15,60 a 45,45 0 1,1 90,0 a 45,45 0 1,1 -90,0" />
    </defs>
    <text className={styles.sealText} textLength="280" lengthAdjust="spacing">
      <textPath href={`#${pathId}`} startOffset="1%">HARMONIZAÇÃO OROFACIAL · JOELANE BITTENCOURT · </textPath>
    </text>
    <text className={styles.sealMark} x="60" y="70" textAnchor="middle">jb.</text>
    <circle cx="8" cy="60" r="1.6" />
    <circle cx="112" cy="60" r="1.6" />
  </svg>;
}

export function AuthorChapter() {
  const root = useRef<HTMLElement>(null);
  const uid = useId().replace(/:/g, '');

  useEffect(() => {
    const section = root.current;
    if (!section) return;

    const media = window.matchMedia('(prefers-reduced-motion: reduce)');
    let observer: IntersectionObserver | undefined;
    let frame = 0;

    const setup = () => {
      observer?.disconnect();
      window.cancelAnimationFrame(frame);
      section.classList.remove(styles.motionReady, styles.motionArmed, styles.motionVisible);

      if (media.matches || !('IntersectionObserver' in window)) return;

      section.classList.add(styles.motionReady);
      void section.offsetWidth;
      frame = window.requestAnimationFrame(() => {
        section.classList.add(styles.motionArmed);
        observer = new IntersectionObserver(([entry]) => {
          if (!entry?.isIntersecting) return;
          section.classList.add(styles.motionVisible);
          observer?.disconnect();
        }, { threshold: .1, rootMargin: '0px 0px -8% 0px' });
        observer.observe(section);
      });
    };

    setup();
    media.addEventListener('change', setup);

    return () => {
      observer?.disconnect();
      window.cancelAnimationFrame(frame);
      media.removeEventListener('change', setup);
    };
  }, []);

  return <section id="sobre" ref={root} className={`${styles.root} doctor-about`} aria-labelledby="author-title">
    <header className={styles.topline} data-author-motion="fade">
      <p>09 / Por trás de cada resultado</p>
      <span aria-hidden="true" />
      <p>A BELEZA TAMBÉM ESTÁ NAS PESSOAS.</p>
    </header>

    <div className={styles.stage}>
      <div className={styles.copy}>
        <h2 id="author-title" aria-label="Dra. Joelane Bittencourt">
          <span className={styles.titleMask}><span data-author-motion="title">Dra. Joelane</span></span>
          <span className={styles.titleMask}><span data-author-motion="title">Bittencourt</span></span>

        </h2>
        <p className={styles.subcopy} data-author-motion="subcopy">Cirurgiã-dentista · {site.cro}<br/>Especialista em Harmonização Orofacial<br/>Atuação voltada ao rejuvenescimento facial e planejamento Full Face</p>
      </div>

      <figure className={styles.photo} data-author-motion="photo">
        <Image
          src={site.images.presentation}
          alt="Retrato profissional da Dra. Joelane Bittencourt"
          fill
          sizes="(max-width: 700px) 88vw, (max-width: 1600px) 46vw, 680px"
        />
      </figure>

      <article className={styles.card} data-author-motion="card">
        <p className={styles.cardLabel}>DRA. JOELANE BITTENCOURT</p>
        <p className={styles.cardCopy}>Acredito em resultados construídos com critério, planejamento e respeito à identidade de cada paciente.</p>
        <details className="professional-details"><summary>Minha abordagem</summary>{biography.split('\n\n').map(paragraph=><p key={paragraph}>{paragraph}</p>)}</details>
        <a className={styles.cta} href={site.instagram} target="_blank" rel="noreferrer">
          <span>Conheça meu trabalho</span>
          <span className={styles.ctaCircle} aria-hidden="true"><ArrowUpRight size={24} strokeWidth={1.25} /></span>
        </a>
      </article>

      <aside className={styles.sideNote} aria-label="Mais que tratamentos, pessoas.">
        <span>MAIS QUE TRATAMENTOS, PESSOAS.</span>
        <i aria-hidden="true" />
        <b aria-hidden="true" />
      </aside>

      <svg className={`${styles.thread} ${styles.threadDesktop}`} viewBox="0 0 1600 110" preserveAspectRatio="none" aria-hidden="true" focusable="false">
        <defs>
          <radialGradient id={`${uid}-author-pearl`} cx="30%" cy="25%">
            <stop stopColor="#faf1de" />
            <stop offset=".5" stopColor="#bea16e" />
            <stop offset="1" stopColor="#765c39" />
          </radialGradient>
        </defs>
        <path d="M -30 30 C 260 84 540 91 800 58 C 1065 25 1320 91 1630 27" pathLength="1" vectorEffect="non-scaling-stroke" data-author-motion="line" />
        <circle cx="800" cy="58" r="8" fill={`url(#${uid}-author-pearl)`} data-author-motion="bead" />
      </svg>

      <svg className={`${styles.thread} ${styles.threadMobile}`} viewBox="0 0 430 546" preserveAspectRatio="none" aria-hidden="true" focusable="false">
        <defs>
          <radialGradient id={`${uid}-author-pearl-mobile`} cx="30%" cy="25%">
            <stop stopColor="#faf1de" />
            <stop offset=".5" stopColor="#bea16e" />
            <stop offset="1" stopColor="#765c39" />
          </radialGradient>
        </defs>
        <path d="M -20 475 C 55 498 90 529 150 538 C 236 551 335 543 450 518" pathLength="1" vectorEffect="non-scaling-stroke" data-author-motion="line" />
        <circle cx="99" cy="524" r="6.5" fill={`url(#${uid}-author-pearl-mobile)`} data-author-motion="bead" />
      </svg>
    </div>

    <footer className={styles.closing}>
      <p className={styles.closingEyebrow} data-author-motion="final"><span />NOSSA FILOSOFIA DE CUIDADO<span /></p>
      <div className={styles.closingRow}>
        <div className={styles.closingMonogram} aria-hidden="true"><strong>jb.</strong><span /></div>
        <p className={styles.closingStatement}>
          <span data-author-motion="final">Por trás de cada resultado, existe uma pessoa.</span>{' '}
          <em data-author-motion="final">E é por isso que estética, para mim, não deve apagar quem você é.</em>
        </p>
        <div className={styles.closingSeal}><span aria-hidden="true" /><BrandSeal id={uid} /></div>
      </div>
    </footer>
  </section>;
}
