/* TPC Films main app (cream paper edition) */
const { useState, useEffect, useRef } = React;

// ---------- Nav ----------
function Nav() {
  const [shrunk, setShrunk] = useState(false);
  useEffect(() => {
    const on = () => setShrunk(window.scrollY > 40);
    window.addEventListener("scroll", on);
    return () => window.removeEventListener("scroll", on);
  }, []);
  return (
    <nav className={"nav" + (shrunk ? " shrunk" : "")}>
      <a href="#top" className="nav-brand">
        <span className="dot"></span>
        T.P.C
      </a>
      <div className="nav-links">
        <a href="#work">Work</a>
        <a href="#about">About</a>
        <a href="#podcast">Podcast</a>
        <a href="#words">Words</a>
        <a href="#contact" className="book">Book a Shoot →</a>
      </div>
    </nav>
  );
}

// ---------- Hero ----------
function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-content">
        <div className="reveal">
          <h1 className="hero-title">
            Stories<br/>
            That <span className="brush-word">Feel</span><br/>
            <span className="outline">Like</span> Cinema.
          </h1>
          <div className="hero-sub">
            <p>Videography, photography, podcasts, and visual storytelling. Filmed on glass, finished by hand.</p>
          </div>
          <div className="hero-cta">
            <a href="#work" className="btn btn-primary">
              View Work <span className="arrow">→</span>
            </a>
            <a href="#contact" className="btn btn-ghost">
              Book a Shoot
            </a>
          </div>
        </div>

        <div className="hero-logo reveal delay-2">
          <div className="caption">A creative film studio</div>
          <img src="assets/tpc-logo.png" alt="TPC Films logo" />
          <div className="ticks">
            <span></span><span></span><span></span><span></span>
          </div>
          <div className="caption-r">Est. 2019</div>
        </div>
      </div>

      <div className="hero-foot">
        <div>Scroll ↓</div>
        <div className="mid">Filmed on glass · Finished by hand</div>
        <div>Reel 04 · 2026</div>
      </div>
    </section>
  );
}

// ---------- Film strip divider ----------
function FilmStrip({ words }) {
  const items = words || [
    "Cinema", "★", "Feel", "·", "Grain", "★", "Light", "·",
    "Story", "★", "35mm", "·", "Frame", "★", "Cut", "·",
  ];
  return (
    <div className="filmstrip">
      <div className="filmstrip-inner">
        {[...items, ...items, ...items].map((w, i) => {
          if (w === "★") return <b key={i}>★</b>;
          if (w === "·") return <i key={i}>·</i>;
          return <span key={i}>{w}</span>;
        })}
      </div>
    </div>
  );
}

// ---------- About ----------
function About() {
  const roles = [
    { num: "01", title: "Director / Videographer", tag: "EST. 2019" },
    { num: "02", title: "Photographer", tag: "FUJI · LEICA" },
    { num: "03", title: "Founder & CEO", tag: "TPC FILMS" },
    { num: "04", title: "Navy Corpsman", tag: "FMF · VETERAN", brush: "FMF" },
    { num: "05", title: "Podcast Engineer", tag: "CINEMATIC AUDIO" },
    { num: "06", title: "Follower of Christ", tag: "GRATEFUL" },
  ];
  return (
    <section className="block about" id="about">
      <div className="block-header reveal">
        <div>
          <div className="block-eyebrow">Chapter 02 · About</div>
          <h2 className="block-title">
            One man. <span className="brush-word">Many</span><br/>
            <span className="outline">stories</span> to tell.
          </h2>
        </div>
        <p className="block-lead">
          TPC is a director, photographer, and audio engineer building TPC Films out of a love for cinema that lingers and stories told slow enough to feel.
        </p>
      </div>

      <div className="about-grid">
        <div className="portrait reveal delay-1">
          <div className="portrait-img"></div>
          <div className="portrait-perforations left">
            {Array.from({length: 8}).map((_,i) => <i key={i} />)}
          </div>
          <div className="portrait-perforations right">
            {Array.from({length: 8}).map((_,i) => <i key={i} />)}
          </div>
          <div className="frame-corners">
            <span></span><span></span><span></span><span></span>
          </div>
        </div>

        <div className="reveal delay-2">
          <div className="bio-list">
            {roles.map(r => (
              <div className="bio-row" key={r.num}>
                <div className="bio-num">{r.num}</div>
                <div className="bio-title">
                  {r.title}
                  {r.brush && <span className="brush">({r.brush})</span>}
                </div>
                <div className="bio-tag">{r.tag}</div>
              </div>
            ))}
          </div>
          <div className="bio-quote">
            "I make films the way I learned to take photographs in the Navy: slow, honest, with the lens close enough to see somebody's hands shake."
            <span>TPC, founder · TPC Films</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Work / Bento ----------
const PROJECTS = [
  { id: "p1", cat: "Commercial", name: "URBAN EDGE", runtime: "01:42", side: "DIR / DP", cls: "t-1", brushed: false, filter: "Commercials", img: "images/2663547265492648254.jpg" },
  { id: "p2", cat: "Music Video", name: "Low Tide", runtime: "03:18", side: "DIR", cls: "t-2", brushed: true, filter: "Music Videos", img: "images/1906917647935436152.jpg" },
  { id: "p3", cat: "Short Film", name: "FATHER, SON.", runtime: "12:04", side: "DIR / W", cls: "t-3", brushed: false, filter: "Short Films", img: "images/2717936130198375792.jpg" },
  { id: "p4", cat: "Podcast", name: "Smoke Room", runtime: "S02", side: "ENG", cls: "t-4", brushed: true, filter: "Podcasts", img: "images/2487396734949832906.jpg" },
  { id: "p5", cat: "Lifestyle", name: "SLOW MORNING", runtime: "02:55", side: "DP", cls: "t-5", brushed: false, filter: "Lifestyle", img: "images/2665900029214088932_2665900025279840525.jpg" },
  { id: "p6", cat: "Commercial", name: "MARLOWE", runtime: "00:60", side: "DIR / DP", cls: "t-6", brushed: false, filter: "Commercials", img: "images/2629656715141001874.jpg" },
  { id: "p7", cat: "Music Video", name: "Hold the Line", runtime: "04:01", side: "DIR", cls: "t-7", brushed: true, filter: "Music Videos", img: "images/2625926475217713633.jpg" },
  { id: "p8", cat: "Lifestyle", name: "GULF COAST", runtime: "02:21", side: "DP / ED", cls: "t-8", brushed: false, filter: "Lifestyle", img: "images/2852852072104095713.jpg" },
];

const FILTERS = ["All", "Commercials", "Music Videos", "Podcasts", "Lifestyle", "Short Films"];

function Work() {
  const [filter, setFilter] = useState("All");
  return (
    <section className="work" id="work">
      <div className="work-inner">
        <div className="block-header reveal">
          <div>
            <div className="block-eyebrow">Chapter 03 · Featured Work</div>
            <h2 className="block-title">
              Selected <span className="brush-word">Reel</span><br/>
              <span className="outline">Vol.</span> Four
            </h2>
          </div>
          <p className="block-lead">
            A working catalog of the last eighteen months. Hover any frame to feel it burn.
          </p>
        </div>

        <div className="work-filters reveal">
          {FILTERS.map(f => (
            <button
              key={f}
              className={"work-filter" + (filter === f ? " active" : "")}
              onClick={() => setFilter(f)}
            >
              {f}
            </button>
          ))}
        </div>

        <div className="bento">
          {PROJECTS.map(p => {
            const dim = filter !== "All" && p.filter !== filter;
            return (
              <div
                key={p.id}
                className={"tile " + p.cls + " reveal"}
                style={{ opacity: dim ? 0.18 : undefined, filter: dim ? "grayscale(1)" : undefined, transition: "opacity 0.4s, filter 0.4s, transform 0.5s" }}
              >
                <div className="tile-runtime">{p.runtime}</div>
                <div className="tile-side">{p.side}</div>
                <div className="tile-img" style={{ backgroundImage: `url('${p.img}')` }}></div>
                <div className="tile-meta">
                  <div className="tile-cat">{p.cat}</div>
                  <div className={"tile-name" + (p.brushed ? " brushed" : "")}>{p.name}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ---------- Podcast / Waveform ----------
function Waveform({ playing }) {
  const canvasRef = useRef(null);
  const rafRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const resize = () => {
      const dpr = window.devicePixelRatio || 1;
      canvas.width = canvas.clientWidth * dpr;
      canvas.height = canvas.clientHeight * dpr;
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.scale(dpr, dpr);
    };
    resize();
    window.addEventListener("resize", resize);

    const bars = 80;
    let phase = 0;

    const draw = () => {
      const w = canvas.clientWidth;
      const h = canvas.clientHeight;
      ctx.clearRect(0, 0, w, h);
      const barW = w / bars;
      const gap = 2;
      for (let i = 0; i < bars; i++) {
        const t = phase + i * 0.18;
        const env = Math.sin(i / bars * Math.PI);
        const base = 0.18 + 0.32 * env;
        const wob = playing
          ? base + 0.4 * (Math.sin(t) * 0.5 + 0.5) * env + 0.18 * (Math.sin(t * 2.7) * 0.5 + 0.5)
          : base + 0.04 * (Math.sin(t * 0.6) * 0.5 + 0.5);
        const bh = Math.max(2, wob * h * 0.85);
        const y = (h - bh) / 2;
        const x = i * barW + gap / 2;
        const grad = ctx.createLinearGradient(0, y, 0, y + bh);
        grad.addColorStop(0, "#d97a1f");
        grad.addColorStop(0.5, "#f1e8d4");
        grad.addColorStop(1, "#b8651a");
        ctx.fillStyle = grad;
        ctx.fillRect(x, y, barW - gap, bh);
      }
      phase += playing ? 0.08 : 0.012;
      rafRef.current = requestAnimationFrame(draw);
    };
    draw();
    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener("resize", resize);
    };
  }, [playing]);

  return <canvas ref={canvasRef}></canvas>;
}

function Podcast() {
  const [playing, setPlaying] = useState(true);
  return (
    <section className="podcast" id="podcast">
      <div className="podcast-inner">
        <div className="podcast-left reveal">
          <div className="podcast-tag">Chapter 04 · Sound</div>
          <h2 className="podcast-headline">
            Cinematic<br/>
            <span className="brush-word">podcast</span><br/>
            <span className="outline">engineering.</span>
          </h2>
          <p className="podcast-copy">
            Treated rooms. Hand-tuned mics. Mixing that breathes like a film score, not a Zoom call.
          </p>
          <div className="podcast-stats">
            <div>
              <h4>140+</h4>
              <p>Episodes engineered</p>
            </div>
            <div>
              <h4>12</h4>
              <p>Shows in production</p>
            </div>
            <div>
              <h4>4.9★</h4>
              <p>Avg. studio review</p>
            </div>
          </div>
        </div>

        <div className="studio reveal delay-1">
          <div className="studio-display">
            <div className="mic">CH 01 / SM7B</div>
            <div className="ep">Ep. 047</div>
            <div className="ep-title">The Long Take</div>
            <div className="ep-host">Hosted by TPC · 1h 12m</div>
          </div>
          <div className="waveform">
            <Waveform playing={playing} />
          </div>
          <div className="studio-controls">
            <button className="play-btn" onClick={() => setPlaying(p => !p)}>
              {playing ? (
                <svg width="14" height="14" viewBox="0 0 14 14"><rect x="2" y="2" width="3.5" height="10" fill="currentColor"/><rect x="8.5" y="2" width="3.5" height="10" fill="currentColor"/></svg>
              ) : (
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 2 L12 7 L3 12 Z" fill="currentColor"/></svg>
              )}
            </button>
            <div className="progress"><div className="progress-fill"></div></div>
            <div>28:14</div>
            <div style={{opacity: 0.5}}>· 1:12:00</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Testimonials ----------
const QUOTES = [
  {
    quote: "TPC made my brand feel like a film. People stop scrolling now.",
    name: "Maren Ortiz",
    role: "Founder · Ember & Oak",
    initial: "M",
  },
  {
    quote: "The patience on set was unreal. He waited for the light, and we got the shot.",
    name: "Caleb Rhys",
    role: "Artist · LowTide",
    initial: "C",
  },
  {
    quote: "Our podcast went from 'good audio' to a sound you can sit inside.",
    name: "Jordan Pace",
    role: "Host · The Long Take",
    initial: "J",
  },
];

function Testimonials() {
  return (
    <section className="testimonials" id="words">
      <div className="test-inner">
        <div className="block-header reveal">
          <div>
            <div className="block-eyebrow">Chapter 05 · Words</div>
            <h2 className="block-title">
              Kind <span className="brush-word">words</span>,<br/>
              <span className="outline">honest</span> rooms.
            </h2>
          </div>
          <p className="block-lead">
            A few of the folks we've made things with.
          </p>
        </div>

        <div className="test-grid">
          {QUOTES.map((q, i) => (
            <div key={i} className={"test-card reveal delay-" + (i+1)}>
              <div className="test-stars">★ ★ ★ ★ ★</div>
              <div className="test-quote">"{q.quote}"</div>
              <div className="test-cite">
                <div className="test-avatar">{q.initial}</div>
                <div>
                  <div className="test-name">{q.name}</div>
                  <div className="test-role">{q.role}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Contact ----------
function Field({ label, type = "text", num, value, onChange, full, children }) {
  const [focus, setFocus] = useState(false);
  const has = value && value.length > 0;
  const cls = "field" + (focus ? " focus" : "") + (has ? " has-value" : "") + (full ? " full" : "");
  return (
    <div className={cls}>
      <label>{label}</label>
      {num && <div className="field-num">{num}</div>}
      {children ? children({ onFocus: () => setFocus(true), onBlur: () => setFocus(false) }) : (
        type === "textarea" ? (
          <textarea value={value} onChange={e => onChange(e.target.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} />
        ) : (
          <input type={type} value={value} onChange={e => onChange(e.target.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} />
        )
      )}
    </div>
  );
}

function Contact() {
  const [form, setForm] = useState({ name: "", email: "", project: "Commercial", budget: "", date: "", details: "" });
  const [sent, setSent] = useState(false);
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.details) return;
    setSent(true);
  };

  return (
    <section className="contact" id="contact">
      <div className="contact-inner">
        <h2 className="contact-headline reveal">
          Let's create<br/>
          something <span className="brush-word">timeless.</span>
        </h2>
        <p className="contact-sub reveal delay-1">
          Tell me about the project, even if it's just a feeling.
        </p>

        {sent ? (
          <div className="thank-you reveal">
            <div className="brush">Cut. Print.</div>
            <p>Got it. I'll be in touch within 48 hours.</p>
          </div>
        ) : (
          <form className="form reveal delay-2" onSubmit={submit}>
            <Field label="Your Name" num="01" value={form.name} onChange={v => update("name", v)} />
            <Field label="Email" type="email" num="02" value={form.email} onChange={v => update("email", v)} />
            <Field label="Project Type" num="03" value={form.project}>
              {({ onFocus, onBlur }) => (
                <select value={form.project} onChange={e => update("project", e.target.value)} onFocus={onFocus} onBlur={onBlur}
                  style={{ appearance: "none", background: "transparent", color: "var(--ink)", border: "none", outline: "none", fontSize: 17, fontFamily: "DM Sans, sans-serif", padding: "6px 0", width: "100%" }}>
                  {["Commercial", "Music Video", "Short Film", "Brand Film", "Podcast", "Photography", "Something Else"].map(o => (
                    <option key={o} value={o}>{o}</option>
                  ))}
                </select>
              )}
            </Field>
            <Field label="Estimated Budget" num="04" value={form.budget} onChange={v => update("budget", v)} />
            <Field label="Shoot Window" num="05" value={form.date} onChange={v => update("date", v)} />
            <div className="field" style={{ borderColor: "transparent", padding: 0 }}></div>
            <Field label="Tell me about it" type="textarea" num="06" value={form.details} onChange={v => update("details", v)} full />

            <div className="submit-row full">
              <div className="legal">
                By submitting you agree to be contacted about your project.
              </div>
              <button type="submit" className="btn btn-primary">
                Send the Pitch <span className="arrow">→</span>
              </button>
            </div>
          </form>
        )}
      </div>
    </section>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-brand">
          <span className="brush">T.P.C Films</span>
          <p>"Stories that feel like cinema."</p>
        </div>
        <div>
          <h5>Studio</h5>
          <ul>
            <li><a href="#work">Featured Work</a></li>
            <li><a href="#about">About TPC</a></li>
            <li><a href="#podcast">Podcast Engineering</a></li>
            <li><a href="#words">Testimonials</a></li>
          </ul>
        </div>
        <div>
          <h5>Services</h5>
          <ul>
            <li><a href="#contact">Commercials</a></li>
            <li><a href="#contact">Music Videos</a></li>
            <li><a href="#contact">Short Films</a></li>
            <li><a href="#contact">Photography</a></li>
          </ul>
        </div>
        <div>
          <h5>Contact</h5>
          <ul>
            <li><a href="mailto:hello@tpcfilms.co">hello@tpcfilms.co</a></li>
            <li><a href="#">Instagram</a></li>
            <li><a href="#">Vimeo</a></li>
            <li><a href="#">YouTube</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <div>© 2026 TPC Films · All Rights Reserved</div>
        <div>Filmed on glass · Finished by hand</div>
      </div>
    </footer>
  );
}

// ---------- Scroll reveal observer ----------
function useScrollReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    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 -40px 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ---------- Main App ----------
function App() {
  useScrollReveal();

  return (
    <>
      <Nav />

      <div className="grain"></div>
      <div className="vignette"></div>

      <main>
        <Hero />
        <FilmStrip />
        <About />
        <FilmStrip words={["Reel", "★", "Take", "·", "Cut", "★", "Burn", "·", "Frame", "★", "Story", "·"]} />
        <Work />
        <Podcast />
        <Testimonials />
        <Contact />
        <Footer />
      </main>
    </>
  );
}

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