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

// Intersection-observer based reveal
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {e.target.classList.add('in');io.unobserve(e.target);}
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -10% 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// soft cursor follower (decorative)
function CursorRing() {
  const r = useRef(null);
  useEffect(() => {
    let x = 0,y = 0,tx = 0,ty = 0,raf;
    const onMove = (e) => {tx = e.clientX;ty = e.clientY;};
    const tick = () => {
      x += (tx - x) * 0.18;y += (ty - y) * 0.18;
      if (r.current) r.current.style.transform = `translate3d(${x - 14}px, ${y - 14}px, 0)`;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    tick();
    return () => {window.removeEventListener('mousemove', onMove);cancelAnimationFrame(raf);};
  }, []);
  return <div ref={r} className="cursor-ring" style={{
    position: 'fixed', left: 0, top: 0, width: 28, height: 28, borderRadius: '50%',
    border: '1px solid rgba(34,31,26,.25)', pointerEvents: 'none', zIndex: 1000,
    mixBlendMode: 'multiply',
    transition: 'width .25s ease, height .25s ease, border-color .25s ease'
  }} />;
}

// Phone mock used in hero — recreates the wireframe vibe but original
function PhoneMock() {
  return (
    <div className="phone">
      <div className="phone-notch" />
      <div className="phone-status">
        <span>9:41</span>
        <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <svg width="16" height="11" viewBox="0 0 16 11" fill="none"><path d="M1 6.5L4 9 15 1.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" /></svg>
          <svg width="22" height="10" viewBox="0 0 22 10" fill="none"><rect x=".5" y=".5" width="18" height="9" rx="2" stroke="currentColor" /><rect x="2" y="2" width="14" height="6" rx="1" fill="currentColor" /><rect x="19.5" y="3.5" width="1.5" height="3" rx=".5" fill="currentColor" /></svg>
        </span>
      </div>
      <div className="phone-screen">
        <div style={{ padding: '4px 4px 0' }}>
          <div className="phone-greet">Good morning, <span className="it"></span></div>
          <div className="phone-sub">Day 14 of your cycle, your bright window</div>
          <div className="phone-date">Thursday, May 14</div>
        </div>
        <div className="phone-cyclewrap">
          <div className="phone-cycle">
            <div className="num">14</div>
            <div className="lbl">day of cycle</div>
            <div className="pill">ovulatory</div>
          </div>
        </div>
        <div className="phone-card">
          <div className="tag">
            <span>today's insight</span>
            <span style={{ fontSize: 11, color: 'var(--ink-2)' }}>✦</span>
          </div>
          <h4>Energy peaks. Make space for what you love.</h4>
          <p>Estrogen lifts mood and stamina mid-cycle. A good week to schedule the harder conversation, the longer run, the bigger ask.</p>
          <span className="more">See more insights →</span>
        </div>
        <div className="phone-dock">
          <div className="ic active">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="1" y="1" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.2" /><rect x="8" y="1" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.2" /><rect x="1" y="8" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.2" /><rect x="8" y="8" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.2" /></svg>
          </div>
          <div className="ic">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="1" y="2" width="12" height="11" rx="1.5" stroke="currentColor" strokeWidth="1.2" /><path d="M4 0v3M10 0v3M1 5h12" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" /></svg>
          </div>
          <div className="ic">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M11 7.5a4.5 4.5 0 0 1-5.5-5.5 5 5 0 1 0 5.5 5.5z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round" /></svg>
          </div>
          <div className="ic">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1l1.4 4.1H12l-3 2.4 1.2 3.8L7 9l-3.2 2.3L5 7.5 2 5.1h3.6L7 1z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round" /></svg>
          </div>
          <div className="ic">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="2" stroke="currentColor" strokeWidth="1.2" /><path d="M7 1v2M7 11v2M1 7h2M11 7h2M3 3l1.5 1.5M9.5 9.5L11 11M3 11l1.5-1.5M9.5 4.5L11 3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" /></svg>
          </div>
        </div>
      </div>
    </div>);

}

function Wordmark({ variant = 'dark' }) {
  const src = variant === 'light' ? 'assets/ayla-white-logo.svg' : 'assets/ayla-black-logo.svg';
  return (
    <img
      src={src}
      alt="Ayla"
      className="wordmark"
      style={{ height: 50, width: 'auto', display: 'block' }}
    />
  );
}

function formatPostTags(post, max) {
  const tags = (post && post.tags) || [];
  const slice = max ? tags.slice(0, max) : tags;
  return slice.join(' · ');
}

var BLOG_FILTER_TAGS = ['Hormones', 'Nutrition', 'Movement', 'Research', 'Lifestyle'];

function blogFilterTags() {
  return ['All'].concat(BLOG_FILTER_TAGS);
}

function postHasTag(post, tag) {
  return (post.tags || []).indexOf(tag) !== -1;
}

function PostBreadcrumb({ slug, setRoute }) {
  const meta = window.AylaPosts && window.AylaPosts.getMeta(slug);
  if (!meta) return null;
  const tagLine = formatPostTags(meta);
  return (
    <div className="breadcrumb">
      <a href={AylaRouter.pathFor('journal')} onClick={(e) => { e.preventDefault(); setRoute('journal'); }}>Blog</a>
      {tagLine ? ' · ' + tagLine : ''}{' · '}{meta.read}
    </div>
  );
}

var AUTHOR_HEADSHOTS = {
  'Ayesha Hafeez': '/assets/ayesha-headshot-cropped.png',
  'Tania Tahooni': '/assets/tania-headshot-cropped.png',
};

function PostByline({ slug }) {
  const meta = window.AylaPosts && window.AylaPosts.getMeta(slug);
  if (!meta) return null;
  const authors = meta.authors || ['Tania Tahooni'];
  const isCoauthored = authors.length > 1;
  return (
    <div className={'byline' + (isCoauthored ? ' byline-coauthors' : '')}>
      <div className="byline-avatars" aria-hidden="true">
        {authors.map(function (name) {
          const src = AUTHOR_HEADSHOTS[name];
          return src ? <img key={name} src={src} alt="" /> : null;
        })}
      </div>
      <div className="meta">
        <b>{authors.join(' & ')}</b>
        <div>{isCoauthored ? 'Co-founders' : 'Co-founder'} at Ayla · Published {meta.date}</div>
      </div>
    </div>
  );
}

function ReadNext({ slug, setRoute }) {
  const posts = (window.POSTS || []).filter(function (p) { return p.slug; });
  const i = posts.findIndex(function (p) { return p.slug === slug; });
  const picks = i >= 0
    ? posts.slice(i + 1, i + 4)
    : posts.slice(0, 3).filter(function (p) { return p.slug !== slug; });
  if (!picks.length) return null;
  const tones = ['lavender', 'rose', 'sage'];
  return (
    <section className="shell read-next">
      <h3>Read next.</h3>
      <div className="journal">
        {picks.map(function (p, j) {
          const route = 'journal-post:' + p.slug;
          const tone = p.tone || tones[j % tones.length];
          return (
            <article className="j-card reveal" role="link" tabIndex={0} key={p.slug}
              onClick={() => setRoute(route)}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setRoute(route); } }}
              style={{ cursor: 'pointer', transitionDelay: (j * 0.08) + 's' }}>
              <div className={'j-thumb' + (p.image ? '' : ' ph ' + tone)}>
                {p.image
                  ? <img src={p.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit', display: 'block' }} />
                  : <span className="ph-tag">blog image</span>}
              </div>
              <div className="j-meta"><span>{formatPostTags(p)}</span><span>· {p.read}</span></div>
              <h3>{p.title}</h3>
              <p>{p.dek}</p>
            </article>
          );
        })}
      </div>
    </section>
  );
}

function postAt(index) {
  return (window.POSTS || [])[index];
}

function postShareUrl(slug) {
  const path = AylaRouter.pathFor('journal-post:' + slug);
  const origin = window.location.origin;
  return origin && origin !== 'null' ? origin + path : path;
}

function prefersNativeShare() {
  return typeof navigator.share === 'function' &&
    window.matchMedia('(max-width: 768px)').matches;
}

async function copyText(text) {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    await navigator.clipboard.writeText(text);
    return true;
  }
  const ta = document.createElement('textarea');
  ta.value = text;
  ta.setAttribute('readonly', '');
  ta.style.cssText = 'position:fixed;left:-9999px';
  document.body.appendChild(ta);
  ta.select();
  const ok = document.execCommand('copy');
  document.body.removeChild(ta);
  return ok;
}

async function shareBlogPost(slug) {
  const meta = AylaPosts && AylaPosts.getMeta(slug);
  const url = postShareUrl(slug);
  const title = (meta && meta.title) || 'Ayla';
  const text = (meta && meta.dek) || '';

  if (prefersNativeShare()) {
    try {
      await navigator.share({ title, text, url });
      return 'shared';
    } catch (err) {
      if (err && err.name === 'AbortError') return false;
    }
  }

  try {
    if (await copyText(url)) return 'copied';
  } catch (e) {}
  return false;
}

function ArticleTools({ slug, progress }) {
  const [shareHint, setShareHint] = useState('Share');

  const onShare = async function () {
    const result = await shareBlogPost(slug);
    if (result === 'copied') {
      setShareHint('Link copied');
      window.setTimeout(function () { setShareHint('Share'); }, 2000);
    }
  };

  return (
    <div className="article-tools" style={{ marginTop: 100 }}>
      <button type="button" title="Save">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 1.5h8v11l-4-2.5-4 2.5v-11z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/></svg>
      </button>
      <button type="button" title={shareHint} aria-label={shareHint} onClick={onShare}>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="3" cy="7" r="1.7" stroke="currentColor" strokeWidth="1.2"/><circle cx="11" cy="3" r="1.7" stroke="currentColor" strokeWidth="1.2"/><circle cx="11" cy="11" r="1.7" stroke="currentColor" strokeWidth="1.2"/><path d="M4.5 6L9.5 4M4.5 8l5 2" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>
      </button>
      <button type="button" title="Listen">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 5v4l3 2V3L3 5zM3 5H1.5v4H3M9 5a2.5 2.5 0 0 1 0 4M11 3a5 5 0 0 1 0 8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      <div style={{
        writingMode: 'vertical-rl', fontSize: 10, letterSpacing: '.2em',
        textTransform: 'uppercase', color: 'var(--ink-3)', marginTop: 14,
      }}>{Math.round(progress)}% read</div>
    </div>
  );
}

Object.assign(window, {
  useReveal, CursorRing, PhoneMock, Wordmark, BLOG_FILTER_TAGS, formatPostTags, blogFilterTags, postHasTag,
  PostBreadcrumb, PostByline, ReadNext, postAt, postShareUrl, shareBlogPost, ArticleTools,
});