const { useState, useEffect, useRef } = React;

/* ---------- TWEAKS COMPONENT ---------- */
function TweaksUI() {
  const [showMetaRow, setShowMetaRow] = useState(false);
  const [contactHeading, setContactHeading] = useState("Let's work together.");
  const [animSpeed, setAnimSpeed] = useState(100);

  useEffect(() => {
    // Register tweaks handler
    const onMessage = (e) => {
      if (e.data.type === '__activate_edit_mode') {
        document.body.classList.add('tweaks-active');
      } else if (e.data.type === '__deactivate_edit_mode') {
        document.body.classList.remove('tweaks-active');
      }
    };
    window.addEventListener('message', onMessage);

    // Announce availability
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');

    return () => window.removeEventListener('message', onMessage);
  }, []);

  return (
    <div id="tweaks-panel" style={{
      display: 'none',
      position: 'fixed',
      bottom: 20,
      right: 20,
      width: 320,
      maxHeight: '70vh',
      background: 'rgba(0,0,0,0.92)',
      border: '1px solid rgba(255,255,255,0.16)',
      borderRadius: 16,
      padding: 24,
      zIndex: 9999,
      color: 'white',
      fontFamily: '"Geist", sans-serif',
      fontSize: 14,
      overflow: 'auto',
      backdropFilter: 'blur(20px)'
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Tweaks</h3>
        <button
          onClick={() => {
            document.getElementById('tweaks-panel').style.display = 'none';
            window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
          }}
          style={{
            background: 'rgba(255,255,255,0.12)',
            border: 'none',
            color: 'white',
            width: 24,
            height: 24,
            borderRadius: '50%',
            cursor: 'pointer',
            fontSize: 16,
            lineHeight: 1,
            display: 'grid',
            placeItems: 'center'
          }}>
          
          ✕
        </button>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {/* Toggle hero meta row */}
        <div>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', marginBottom: 6 }}>
            <input
              type="checkbox"
              checked={showMetaRow}
              onChange={(e) => {
                setShowMetaRow(e.target.checked);
                document.querySelector('.hero-meta-row').style.display = e.target.checked ? 'flex' : 'none';
              }}
              style={{ cursor: 'pointer' }} />
            
            <span>Show hero meta row</span>
          </label>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>Languages & availability</div>
        </div>

        {/* Contact heading text */}
        <div>
          <label style={{ display: 'block', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginBottom: 8 }}>Contact heading</label>
          <input
            type="text"
            value={contactHeading}
            onChange={(e) => {
              setContactHeading(e.target.value);
              const h = document.querySelector('.contact h2');
              if (h) h.textContent = e.target.value;
            }}
            style={{
              width: '100%',
              padding: '8px 10px',
              background: 'rgba(255,255,255,0.08)',
              border: '1px solid rgba(255,255,255,0.16)',
              borderRadius: 6,
              color: 'white',
              fontFamily: 'inherit',
              fontSize: 13
            }} />
          
        </div>

        {/* Animation speed */}
        <div>
          <label style={{ display: 'block', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginBottom: 8 }}>
            Word reveal speed: {animSpeed}%
          </label>
          <input
            type="range"
            min="50"
            max="200"
            value={animSpeed}
            onChange={(e) => {
              setAnimSpeed(Number(e.target.value));
              const speed = 720 * (100 / e.target.value) + 'ms';
              const style = document.getElementById('tweaks-animation-override') || (() => {
                const s = document.createElement('style');
                s.id = 'tweaks-animation-override';
                document.head.appendChild(s);
                return s;
              })();
              style.textContent = `.split-words .word { transition-duration: ${speed} !important; }`;
            }}
            style={{ width: '100%', cursor: 'pointer' }} />
          
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)', marginTop: 4 }}>Slower ← → Faster</div>
        </div>
      </div>
    </div>);

}

/* ---------- HERO ---------- */
function Hero() {
  return (
    <header id="top" className="hero">
      <div className="hero-bg"></div>
      <div className="container">
        <h1 className="reveal d1 split-words">
          Hey <span className="wave">👋</span><br />
          I'm <span style={{ color: 'var(--violet)' }}>martina.</span>
        </h1>

        <div className="hero-sub-row reveal d2">
          <p className="hero-tag">
            Growth and marketing systems built around <span className="acc">strategy</span>, story, and execution.
          </p>
          <p className="hero-bio">I help teams turn strategy into growth: campaigns, messaging, positioning, content, lead generation, reporting, automations, and cleaner systems.

          </p>
        </div>

        <div className="hero-stats reveal d3">
          <div className="hero-stat">
            <div className="label">Currently</div>
            <div className="value">Growth & Marketing Lead · <span className="ok">Senturo</span></div>
          </div>
          <div className="hero-stat">
            <div className="label">Focus</div>
            <div className="value">Growth Marketing</div>
          </div>
          <div className="hero-stat">
            <div className="label">Education</div>
            <div className="value">University of
Buckingham</div>
          </div>
          <div className="hero-stat">
            <div className="label"></div>
            <div className="value"></div>
          </div>
        </div>
      </div>
    </header>);
}

/* ---------- WORK PREVIEW ---------- */
function WorkPreview() {
  const featured = window.FEATURED_IDS.map((id) => window.PROJECTS.find((p) => p.id === id));
  const caseStudies = window.PROJECTS.filter((p) => p.caseStudy);
  const cats = ["All", "Case Studies", ...Array.from(new Set(window.PROJECTS.map((p) => p.cat)))];
  const [filter, setFilter] = useState("All");

  let filtered;
  if (filter === "All") filtered = featured;else
  if (filter === "Case Studies") filtered = caseStudies;else
  filtered = window.PROJECTS.filter((p) => p.cat === filter).slice(0, 6);

  return (
    <section id="work" className="section">
      <div className="container">
        <div className="section-head reveal">
          <h2 className="section-title split-words">Case studies, <span className="acc">results</span>, and <span style={{ color: '#212121' }}>projects</span></h2>
          <div className="section-aside">A collection of real projects across growth, content, SEO, outbound, brand strategy, and creative direction.

          </div>
        </div>

        <div className="work-filter reveal d1">
          {cats.map((c) =>
          <button
            key={c}
            className={`chip violet ${filter === c ? "active" : ""}`}
            onClick={() => setFilter(c)}>
              {c}
              <span className="count">
                {c === "All" ? featured.length : c === "Case Studies" ? caseStudies.length : window.PROJECTS.filter((p) => p.cat === c).length}
              </span>
            </button>
          )}
        </div>

        <div className="work-grid reveal d2">
          {filtered.slice(0, 6).map((p) => p && <WorkCard key={p.id} p={p} />)}
        </div>

        <div className="reveal d3" style={{ marginTop: 36, display: "flex", justifyContent: "center" }}>
          <a href="work.html" className="btn btn-secondary">
            See all work
            <ArrowR />
          </a>
        </div>
      </div>
    </section>);

}

/* ---------- QUOTES ---------- */
function Quotes() {
  const [quoteImages, setQuoteImages] = useState({});
  const gridRef = useRef(null);

  useEffect(() => {
    const grid = gridRef.current;
    if (!grid) return;

    const cardWidth = 380 + 18; // card width + gap
    let currentIndex = 0;

    const autoScroll = setInterval(() => {
      currentIndex = (currentIndex + 1) % window.QUOTES.length;
      grid.scrollTo({
        left: currentIndex * cardWidth,
        behavior: 'smooth'
      });
    }, 6000); // 6 seconds per card

    return () => clearInterval(autoScroll);
  }, []);

  return (
    <section className="section quotes">
      <div className="container">
        <div className="section-head reveal">
          <h2 className="section-title split-words"><span style={{ display: 'block' }}>You didn't hear</span><span style={{ display: 'block' }}>this from <span style={{ color: 'var(--black)' }}>me.</span></span></h2>
          <div className="section-aside">
            Borrowed credibility, in their words.
          </div>
        </div>
        <div className="quote-grid reveal d1" ref={gridRef}>
          {window.QUOTES.map((q, i) =>
          <div className="quote-card" key={i}>
              <div className="quote-top">
                <div className="qmark">"</div>
                <blockquote>{q.text}</blockquote>
              </div>
              <div className="quote-author">
                <img
                src={`quote-${q.initials.toLowerCase()}.webp`}
                alt={q.name}
                style={{ width: "40px", height: "40px", borderRadius: "50%", objectFit: "cover", flexShrink: 0, display: "block" }} />
              
                <div>
                  <div className="quote-author-name">{q.name}</div>
                  <div className="quote-author-role">{q.role}</div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ---------- EXPERIENCE CARDS (hover reveal) ---------- */
function ExperienceCards() {
  return (
    <section className="section">
      <div className="container">
        <div className="section-head reveal">
          <h2 className="section-title split-words">Where I've <span className="acc">worked</span></h2>
          <div className="section-aside">
            Hover any card to see everything I did there.
          </div>
        </div>
        <div className="exp-grid reveal d1">
          {window.EXPERIENCE.map((e, i) =>
          <article key={i} className="exp-card">
              <div className="exp-face exp-face-front">
                <div className="exp-face-top">
                  <span>{e.range}</span>
                  <span className="live">{e.initials}</span>
                </div>
                <div className="exp-front-body">
                  <div className="exp-role">{e.role}</div>
                  <div className="exp-company">{e.company}</div>
                </div>
              </div>
              <div className="exp-face exp-face-back">
                <div className="exp-face-top">
                  <span>{e.range}</span>
                  <span>{e.initials}</span>
                </div>
                <div className="exp-back-body">
                  <div className="label">What I did</div>
                  <ul className="exp-bullets">
                    {e.bullets.map((b, j) => <li key={j}>{b}</li>)}
                  </ul>
                </div>
                <div className="exp-role-back">{e.role} <span className="exp-at">·</span> {e.company}</div>
              </div>
            </article>
          )}
        </div>
      </div>
    </section>);

}

/* ---------- PORTRAIT BAND ---------- */
function PortraitBand() {
  return (
    <section className="portrait-band">
      <div className="container">
        <div className="portrait-grid">
          <div className="portrait-meta reveal">
            <span className="eyebrow" style={{ fontFamily: "Helvetica" }}>The face behind the work</span>
            <h2 className="portrait-name split-words">
              Welcome!<br />
              <span className="gradient-text"></span>
            </h2>
            <p className="portrait-lead split-words">
              {(() => {
                const [hoveredWord, setHoveredWord] = React.useState(null);
                const text = "I'm a strategist, creator, and entrepreneur working across marketing, storytelling, and design. I've worked with founders, startups, and global teams to build growth strategies with a creative perspective. Outside of marketing, I design jewelry and love to travel.";
                return text.split(/(\s+)/).map((word, i) =>
                <span
                  key={i}
                  onMouseEnter={() => setHoveredWord(i)}
                  onMouseLeave={() => setHoveredWord(null)}
                  style={{
                    color: hoveredWord === i ? "#c6ff33" : "inherit",
                    cursor: word.trim() ? "pointer" : "default",
                    transition: "color 0.1s ease"
                  }}>
                  {word}</span>
                );
              })()}
            </p>
          </div>
          <div className="portrait-frame reveal d2">
            <img
              src="slot-martina-portrait.webp"
              alt="Martina Vasconez"
              style={{ width: "460px", height: "400px", borderRadius: "22px", objectFit: "cover", display: "block" }} />
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- SKILLS / TOOLS / LANGUAGES ---------- */
function SkillsBlock() {
  return (
    <section className="section quotes">
      <div className="container">
        <div className="section-head reveal">
          <h2 className="section-title split-words">Skills, tools, <span className="acc">languages</span></h2>
          <div className="section-aside">
            The shape of the work, the things I lean on to ship it, and the words I think in.
          </div>
        </div>

        <div className="split-grid reveal d1">
          <div className="skills-list">
            {window.SKILLS.map((s, i) =>
            <div className="skill-row" key={s.title}>
                <div className="idx">0{i + 1}</div>
                <div>
                  <div className="skill-title">{s.title}</div>
                  <div className="skill-tags">
                    {s.tags.map((t) => <span key={t}>{t}</span>)}
                  </div>
                </div>
              </div>
            )}
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>Software I use daily</div>
            <div className="tools-grid">
              {window.TOOLS.map((t) =>
              <div className="tool-pill" key={t}>
                  <span className="dot"></span>
                  {t}
                </div>
              )}
            </div>
          </div>
        </div>

        <div style={{ marginTop: 60 }} className="reveal d2">
          <div className="eyebrow">Languages I speak</div>
          <div className="langs-row">
            {window.LANGUAGES.map((l) =>
            <div className="lang-cell" key={l.name}>
                <div className="lang-name">{l.name}</div>
                <div className="lang-level">{l.level}</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- COMMANDMENTS ---------- */
function Commandments() {
  const [hovered, setHovered] = useState(null);
  const [pos, setPos] = useState({ x: 0, y: 0 });

  const list = [
  { num: "001", text: "POWER REWARDS THE PERSON WHO WORKS FOR IT.", person: "SERENA WILLIAMS", img: "cmd-001-serena.jpg" },
  { num: "002", text: "NEVER NEGOTIATE AGAINST YOUR OWN FEAR.", person: "SIMONE BILES", img: "cmd-002-simone.jpg" },
  { num: "003", text: "PEOPLE RESPECT WHAT YOU PROTECT.", person: "MICHELLE OBAMA", img: "cmd-003-michelle.jpg" },
  { num: "004", text: "ALL CRITICISMS MUST BE ACCOMPANIED BY SUGGESTIONS.", person: "ZAHA HADID", img: "cmd-004-zaha.jpg" },
  { num: "005", text: "TAKE YOUR WORK SERIOUSLY, YOURSELF LESS SO.", person: "FRIDA KAHLO", img: "cmd-005-frida.jpg" },
  { num: "006", text: "NEVER TAKE NO FOR AN ANSWER.", person: "NAPOLEON BONAPARTE", img: "cmd-006-napoleon.jpg" },
  { num: "007", text: "BE PROLIFIC.", person: "MOZART", img: "cmd-007-mozart.jpg" },
  { num: "008", text: "PRACTICE ABUNDANCE.", person: "BEYONCÉ", img: "cmd-008-beyonce.jpg" },
  { num: "009", text: "BE YOUR CLIENT'S MOST LOYAL CUSTOMER.", person: "STEVE JOBS", img: "cmd-009-steve.jpg" },
  { num: "010", text: "MANIFEST YOUR DREAM. THEN BUILD IT.", person: "THOMAS EDISON", img: "cmd-010-edison.jpg" }];


  const [loadedImages, setLoadedImages] = useState({});

  // Lazy load image when row is hovered
  const handleHover = (idx) => {
    setHovered(idx);
    if (!loadedImages[idx] && list[idx].img) {
      const img = new Image();
      img.onload = () => {
        setLoadedImages((prev) => ({ ...prev, [idx]: true }));
      };
      img.src = list[idx].img;
    }
  };

  return (
    <section
      className="cmd-section"
      onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}>
      
      <div className="container">
        <div className="section-head cmd-header reveal">
          <h2 className="section-title split-words cmd-heading">My 10 commandments</h2>
          <div className="section-aside cmd-aside">The rules I live and work by.</div>
        </div>

        <div className="cmd-list reveal d1">
          {list.map((c, i) =>
          <div
            key={i}
            className={`cmd-row${hovered === i ? " cmd-row--on" : hovered !== null ? " cmd-row--off" : ""}`}
            onMouseEnter={() => handleHover(i)}
            onMouseLeave={() => setHovered(null)}>
            
              <span className="cmd-n">{c.num}</span>
              <span className="cmd-t">{c.text}</span>
              <span className="cmd-p">{c.person}</span>
            </div>
          )}
        </div>
      </div>

      {hovered !== null && list[hovered].img &&
      <div
        className="cmd-popup"
        style={{ left: pos.x + 28, top: pos.y - 120 }}>
        
          <img src={list[hovered].img} alt={list[hovered].person} className="cmd-popup-img" />
          <div className="cmd-popup-name">{list[hovered].person}</div>
        </div>
      }

      {hovered !== null && !list[hovered].img &&
      <div
        className="cmd-popup"
        style={{ left: pos.x + 28, top: pos.y - 120 }}>
        
          <div className="cmd-popup-frame">
            <svg className="cmd-popup-icon" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="18" height="18" rx="2"></rect>
              <circle cx="8.5" cy="8.5" r="1.5"></circle>
              <polyline points="21 15 16 10 5 21"></polyline>
            </svg>
            <span className="cmd-popup-hint">add photo</span>
          </div>
          <div className="cmd-popup-name">{list[hovered].person}</div>
        </div>
      }
    </section>);

}

/* ---------- CONTACT ---------- */
function Contact() {
  return (
    <section id="contact" className="contact">
      <div className="contact-bg"></div>
      <div className="container">
        <div className="reveal" style={{ marginBottom: 22 }}>
          <span className="glow-tag" style={{ background: "rgba(255,255,255,0.08)", color: "white", borderColor: "rgba(255,255,255,0.16)" }}>
            <span className="blip"></span>Contact
          </span>
        </div>
        <h2 className="reveal d1 split-words">
          Let's <span className="acc">Talk</span>
        </h2>

        <div className="contact-meta reveal d2" style={{ maxWidth: "300px" }}>
          <div className="contact-meta-row">
            <div className="label">Find me</div>
            <div className="contact-social">
              <a href="https://www.linkedin.com/in/martina-vasconez-579732193" target="_blank" rel="noopener" title="LinkedIn">
                <LinkedIn />
              </a>
            </div>
          </div>
          <div className="contact-meta-row" style={{ marginTop: 32 }}>
            <div className="label">Book a call</div>
            <a href="https://calendly.com/martinavasconez/30min" target="_blank" rel="noopener" className="btn btn-lime">
              Schedule time
              <ArrowR />
            </a>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- APP ---------- */
function App() {
  useReveal();
  useScrollWordReveal();
  return (
    <>
      <Nav active="home" />
      <Hero />
      <PortraitBand />
      <WorkPreview />
      <Quotes />
      <ExperienceCards />
      <Commandments />
      <SkillsBlock />
      <Contact />
      <Footer />
    </>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);