/* global React */
const { useState, useEffect, useRef } = React;

/* ======================================================
   ABOUT
   ====================================================== */
function About() {
  const clients = [
    'Marcas em crescimento', 'Startups e produtos digitais', 'Instituições culturais',
    'Editoras', 'Universidades', 'Organizações de impacto',
    'Empresas de capital aberto', 'Organizações ESG',
  ];
  return (
    <section id="estudio" className="section wrap">
      <div className="section-head">
        <div className="section-num">/01</div>
        <div className="section-label">Studio positioning</div>
      </div>

      <div className="positioning">
        <h2 className="positioning-title reveal">
          <span className="line"><span className="key">Estratégia</span> <span className="mute">antes da estética.</span></span>
          <span className="line"><span className="key">Significado</span> <span className="mute">antes de visibilidade.</span></span>
          <span className="line"><span className="key">Sistema</span> <span className="mute">antes da arte.</span></span>
        </h2>
        <p className="positioning-body reveal">
          Acreditamos que o design vai além da estética. Como ferramenta de
          pensamento, estratégia e construção de valor, ele conecta
          criatividade, cultura e inovação para desenvolver marcas e
          sistemas de comunicação com consistência, relevância e impacto
          duradouro.
        </p>
      </div>

      <div className="who reveal">
        <div className="who-head">
          <div className="section-label">Who we work with</div>
          <p className="who-intro">
            Organizações que acreditam no poder do design para construir
            valor, relevância e legado.
          </p>
        </div>
        <ul className="who-list">
          {clients.map((c, i) => (
            <li key={i}><span className="who-num mono">—</span>{c}</li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ======================================================
   CASES
   ====================================================== */
const CASES = [
  { num: '/01', title: 'Empório da Terra',   meta: ['Strategy', 'Brand Design', 'Digital Experience'],                              year: '2025', sw: '#C9C2B2', swFg: '#0A0A0A', kind: 'poster', short: 'Empório', subtitle: 'da Terra', tag: 'BRAND / 2025', img: 'assets/case-emporio.jpg' },
  { num: '/02', title: 'Black Fish Brasil',  meta: ['Strategy', 'Brand Design', 'Digital Experience', 'Content & Social Systems'], year: '2024', sw: '#0F1B2A', swFg: '#FAFAFA', kind: 'poster', short: 'Black Fish', subtitle: 'Brasil', tag: 'BRAND / 2024', img: 'assets/case-blackfish.jpg' },
  { num: '/03', title: 'Rancho Thands',     meta: ['Strategy', 'Brand Design', 'Digital Experience', 'Content & Social Systems'], year: '2025', sw: '#E2D3BD', swFg: '#0A0A0A', kind: 'type',   short: 'Rancho',  subtitle: 'Thands',  tag: 'BRAND / 2025', img: 'assets/case-rancho.jpg' },
  { num: '/04', title: 'Engenho de Ideias',  meta: ['Digital Experience'],                                                          year: '2024', sw: '#1A1A1A', swFg: '#FAFAFA', kind: 'grid',   short: 'Engenho', subtitle: 'de Ideias', tag: 'DIGITAL', img: 'assets/case-engenho.jpg' },
];

function Cases() {
  return (
    <section id="projetos" className="section wrap">
      <div className="section-head reveal">
        <div className="section-num">/04</div>
        <div>
          <div className="section-label">Work</div>
          <h2 className="display" style={{fontSize:'clamp(40px,5.2vw,84px)', marginTop:18, maxWidth:'15ch'}}>
            Projetos<br/><span style={{color:'var(--mute)'}}>selecionados</span>
          </h2>
          <p className="cases-intro">
            que mostram como estratégia, design e
            comunicação se conectam para gerar valor.
          </p>
        </div>
      </div>

      <div className="stack">
        {CASES.map((c, i) => (
          <article key={c.num} className="stack-card"
            style={{ ['--sc-top']: `calc(108px + ${i * 22}px)`, ['--swatch']: c.sw, ['--swatch-fg']: c.swFg }}>
            <image-slot
              class="sc-bg"
              id={`case-${c.num.replace('/','')}`}
              src={c.img || `assets/concept-${c.num.replace('/','')}.png`}
              shape="rect"
              fit="cover"
              placeholder={`${c.title} — arraste a imagem`}
            ></image-slot>
            <div className="sc-scrim"></div>
            <div className="sc-left">
              <div className="sc-top-row">
                <span></span>
                <span></span>
              </div>
              <div className="sc-main">
                <h3 className="sc-title">{c.title}</h3>
                <div className="sc-meta">
                  {c.meta.map((m, j) => <span key={j} className="chip">{m}</span>)}
                </div>
                <div className="sc-foot">
                  <span className="sc-open is-soon" aria-disabled="true">Coming soon <span className="arr">↗</span></span>
                </div>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

function PreviewArt({ c }) {
  const metaRow = (
    <div className="meta-row">
      <span>{c.tag}</span>
      <span className="pin">{c.year}</span>
    </div>
  );
  switch (c.kind) {
    case 'type':
      return (
        <>
          <div className="pv-type">
            <div className="lbl">— {c.subtitle}</div>
            <div className="big">{c.short}<span className="thin">.</span></div>
          </div>
          {metaRow}
        </>
      );
    case 'grid':
      return (
        <>
          <div className="pv-grid">
            <div className="cell" style={{background:'#3A3A3A'}}><span className="lbl">/01</span></div>
            <div className="cell" style={{background:'#222'}}><span className="lbl">/02</span></div>
            <div className="cell" style={{background:'#FAFAFA', color:'#0A0A0A'}}><span className="lbl">/03</span></div>
            <div className="cell" style={{background:'#0A0A0A'}}><span className="lbl">/04</span></div>
            <div className="cell" style={{background:'#4F4F4F'}}><span className="lbl">/05</span></div>
            <div className="cell" style={{background:'#2A2A2A'}}><span className="lbl">/06</span></div>
            <div className="cell" style={{background:'#FAFAFA', color:'#0A0A0A'}}><span className="lbl">/07</span></div>
            <div className="cell" style={{background:'#1A1A1A'}}><span className="lbl">/08</span></div>
            <div className="cell" style={{background:'#666'}}><span className="lbl">/09</span></div>
          </div>
          {metaRow}
        </>
      );
    case 'spread':
      return (
        <>
          <div className="pv-spread">
            <div className="page">
              <div className="h">{c.short}<span className="thin">_</span></div>
              <div className="l mid" /><div className="l short" /><div className="l short" />
              <div className="l tiny" style={{marginTop:14}} />
            </div>
            <div className="page">
              <div className="l short" style={{marginTop:0}} />
              <div className="l mid" /><div className="l short" /><div className="l mid" /><div className="l short" />
              <div className="l tiny" style={{marginTop:14}} />
            </div>
          </div>
          {metaRow}
        </>
      );
    case 'app':
      return (
        <>
          <div className="pv-app">
            <div className="bar"><span>{c.short}</span><span>●●●</span></div>
            <div>
              <div className="balance-sub">Saldo disponível</div>
              <div className="balance">R$ 12<span className="thin">.480,00</span></div>
            </div>
            <div className="rows">
              <div className="row"><span className="l">Pix</span><span className="v">→</span></div>
              <div className="row"><span className="l">Cartão</span><span className="v">→</span></div>
              <div className="row"><span className="l">Investir</span><span className="v">→</span></div>
            </div>
          </div>
          {metaRow}
        </>
      );
    case 'poster':
      return (
        <>
          <div className="pv-poster" style={{display:'flex', flexDirection:'column', height:'100%'}}>
            <div className="head">
              <div className="lbl">— {c.subtitle}</div>
              <div className="big">{c.short}<span className="thin">.</span></div>
            </div>
            <div className="stripes" style={{flex:1}}>
              <div className="s" /><div className="s" /><div className="s" /><div className="s" /><div className="s" /><div className="s" /><div className="s" /><div className="s" />
            </div>
          </div>
          {metaRow}
        </>
      );
    case 'circle':
      return (
        <>
          <div className="pv-circle" style={{position:'relative', height:'100%'}}>
            <div className="top"><span>{c.subtitle}</span><span>{c.tag}</span></div>
            <div className="sun" />
            <div className="ttl">{c.short}<span style={{fontWeight:200}}>.</span></div>
          </div>
          {metaRow}
        </>
      );
    default: return null;
  }
}

/* ======================================================
   FOUNDER
   ====================================================== */
function Founder() {
  return (
    <section id="fundador" className="section wrap">
      <div className="section-head reveal">
        <div className="section-num">/06</div>
        <div className="section-label">About the founder</div>
      </div>

      <div className="fnd reveal">
        <div className="fnd-main">
          <div className="fnd-figure">
            <img src="assets/foto-thiago.png" alt="Thiago Dalmas Affonso" className="fnd-slot fnd-photo" />
          </div>

          <div className="fnd-text">
            <p>
              Thiago Dalmas Affonso é fundador da Morse e atua há mais de 25
              anos na construção de marcas, narrativas e sistemas de
              comunicação.
            </p>
            <p>
              Formado em Publicidade e Propaganda pela PUCRS, desenvolveu
              projetos para empresas do varejo, indústria e serviços, além de
              instituições públicas e governamentais de diferentes portes e
              contextos.
            </p>
            <p>
              Sua trajetória foi construída conectando estratégia, comunicação
              e design para transformar complexidade em clareza, posicionamentos
              em significado e ideias em experiências capazes de gerar valor
              duradouro.
            </p>
            <p>
              Hoje, lidera a Morse com a mesma convicção que orienta sua
              prática: o design é uma ferramenta de pensamento, capaz de
              construir relevância, fortalecer conexões e ampliar o impacto de
              organizações e iniciativas.
            </p>
            <a className="fnd-ig" href="https://www.linkedin.com/in/thiago-dalmas-affonso/" target="_blank" rel="noreferrer">
              LinkedIn <span className="ig-handle">/thiago-dalmas-affonso</span> <span className="arr">↗</span>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ======================================================
   CONTACT
   ====================================================== */
function ContactTransmit() {
  // M O R S E — real Morse timing, identical to the hero signal
  const WORD = [
    ['dash', 'dash'],            // M
    ['dash', 'dash', 'dash'],    // O
    ['dot', 'dash', 'dot'],      // R
    ['dot', 'dot', 'dot'],       // S
    ['dot'],                     // E
  ];
  const symbols = [];
  WORD.forEach((letter, li) => letter.forEach((t) => symbols.push({ type: t, li })));

  const [active, setActive] = React.useState(-1);

  React.useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) { setActive(-1); return; }
    const unit = 135;
    let idx = 0;
    let timer;
    const run = () => {
      const sym = symbols[idx];
      setActive(idx);
      const onDur = sym.type === 'dash' ? unit * 3 : unit;
      timer = setTimeout(() => {
        setActive(-1);
        const next = symbols[idx + 1];
        let gap = unit;                          // inter-symbol
        if (!next) gap = unit * 7;               // word reset
        else if (next.li !== sym.li) gap = unit * 3; // inter-letter
        timer = setTimeout(() => {
          idx = (idx + 1) % symbols.length;
          run();
        }, gap);
      }, onDur);
    };
    run();
    return () => clearTimeout(timer);
  }, []);

  let gi = -1;
  return (
    <div className="transmit reveal" data-no-i18n aria-hidden="true">
      <div className="transmit-head">
        <span className="sig-live" />
        <span className="transmit-k mono">Transmitting</span>
      </div>
      <div className="transmit-signal">
        {WORD.map((letter, li) => (
          <span className="tx-letter" key={li}>
            {letter.map((t) => {
              gi += 1;
              const cur = gi;
              return (
                <span
                  key={cur}
                  className={`tx ${t}${cur === active ? ' on' : ''}`}
                />
              );
            })}
          </span>
        ))}
      </div>
      <div className="transmit-word mono">M · O · R · S · E</div>
    </div>
  );
}

function Contact() {
  return (
    <section id="contato" className="section wrap contact">
      <div className="section-head reveal">
        <div className="section-num">/07</div>
        <div className="section-label">Let's build something with intention</div>
      </div>

      <div className="cta reveal">
        <div className="cta-lead">
          <h2 className="contact-headline">
            Está construindo<br/><span className="thin mute">algo relevante?</span>
          </h2>
          <p className="cta-sub">
            Queremos conhecer.
          </p>
        </div>

        <a className="cta-action" href="mailto:contato@morsestudio.com.br">
          <span className="cta-action-row">
            <span className="cta-verb">Iniciar uma conversa</span>
            <span className="cta-arrow">↗</span>
          </span>
          <span className="cta-mail mono">contato@morsestudio.com.br</span>
        </a>
      </div>

      <ContactTransmit />

      <div className="contact-grid reveal">
        <div className="contact-card">
          <div className="k">WhatsApp</div>
          <a className="v" href="https://wa.me/5551991599226" target="_blank" rel="noreferrer">+55 51 99159 — 9226 <span className="arr">↗</span></a>
        </div>
        <div className="contact-card">
          <div className="k">Instagram</div>
          <a className="v" href="https://instagram.com/morsestudio_" target="_blank" rel="noreferrer">@morsestudio_ <span className="arr">↗</span></a>
        </div>
        <div className="contact-card">
          <div className="k">LinkedIn</div>
          <a className="v" href="https://www.linkedin.com/company/morsestudio" target="_blank" rel="noreferrer">/morsestudio <span className="arr">↗</span></a>
        </div>
        <div className="contact-card">
          <div className="k">Substack</div>
          <a className="v" href="https://morsecraftdesign.substack.com" target="_blank" rel="noreferrer">@morsecraftdesign <span className="arr">↗</span></a>
        </div>
      </div>
    </section>
  );
}

/* ======================================================
   OUTRO + FOOTER
   ====================================================== */
function Outro() {
  const wordRef = useRef(null);
  useEffect(() => {
    const word = wordRef.current;
    if (!word) return;
    const wrap = word.closest('.wrap');
    let inkRatio = null;
    const measureInkRatio = () => {
      const cs = getComputedStyle(word);
      const probe = 300;
      const ls = -0.06 * probe;
      const c = document.createElement('canvas');
      c.width = Math.ceil(probe * 5.5); c.height = Math.ceil(probe * 1.4);
      const ctx = c.getContext('2d');
      ctx.fillStyle = '#000'; ctx.fillRect(0, 0, c.width, c.height);
      ctx.fillStyle = '#fff'; ctx.textBaseline = 'middle';
      ctx.font = `${cs.fontWeight} ${probe}px ${cs.fontFamily}`;
      let x = 0;
      for (const ch of 'MORSE') { ctx.fillText(ch, x, c.height / 2); x += ctx.measureText(ch).width + ls; }
      const img = ctx.getImageData(0, 0, c.width, c.height).data;
      let minX = c.width, maxX = 0;
      for (let y = 0; y < c.height; y++) for (let xx = 0; xx < c.width; xx++) if (img[(y * c.width + xx) * 4] > 40) { if (xx < minX) minX = xx; if (xx > maxX) maxX = xx; }
      return (maxX - minX) / probe;
    };
    const fit = () => {
      if (!inkRatio) inkRatio = measureInkRatio();
      if (!inkRatio || inkRatio < 0.1) return;
      const cs = getComputedStyle(wrap);
      const inner = wrap.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
      word.style.fontSize = (inner / inkRatio) + 'px';
    };
    const ro = new ResizeObserver(fit);
    ro.observe(wrap);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(() => { inkRatio = null; fit(); });
    fit();
    return () => ro.disconnect();
  }, []);
  return (
    <section className="outro wrap">
      <h2 className="word" ref={wordRef}>MORSE</h2>
      <div className="sub">
        <span>—— ——— ·—· ··· ·</span>
        <span>Craft Design</span>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="wrap foot">
      <div className="foot-col">
        <div className="foot-k">Morse</div>
        <div className="foot-v">Estúdio de Craft Design</div>
      </div>
      <div className="foot-col">
        <div className="foot-k">Contato</div>
        <a className="foot-v link" href="mailto:contato@morsestudio.com.br">contato@morsestudio.com.br</a>
        <a className="foot-v link" href="https://wa.me/5551991599226" target="_blank" rel="noreferrer">WhatsApp +55 51 99159 — 9226</a>
      </div>
      <div className="foot-col">
        <div className="foot-k">Redes</div>
        <a className="foot-v link" href="https://instagram.com/morsestudio_" target="_blank" rel="noreferrer">Instagram ↗</a>
        <a className="foot-v link" href="https://www.linkedin.com/company/morsestudio" target="_blank" rel="noreferrer">LinkedIn ↗</a>
        <a className="foot-v link" href="https://morsecraftdesign.substack.com" target="_blank" rel="noreferrer">Substack ↗</a>
      </div>
      <div className="foot-col foot-end">
        <div className="foot-v">© Morse Craft Design · 2026</div>
        <a className="foot-v link" href="#">Voltar ao topo ↑</a>
      </div>
    </footer>
  );
}

window.About = About;
window.Cases = Cases;
window.Founder = Founder;
window.Contact = Contact;
window.Outro = Outro;
window.Footer = Footer;
