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

// ============================================================
// DESIGN TOKENS
// ============================================================
const PALETTES = {
  amber: { accent: "#E8A24A", accentSoft: "rgba(232,162,74,0.14)", accentDeep: "#C77B1F" },
  rust: { accent: "#D9613A", accentSoft: "rgba(217,97,58,0.14)", accentDeep: "#A8431F" },
  bone: { accent: "#E8DFC8", accentSoft: "rgba(232,223,200,0.14)", accentDeep: "#B9AC8C" },
  ice: { accent: "#9EC9D9", accentSoft: "rgba(158,201,217,0.14)", accentDeep: "#5D8FA3" }
};

// ============================================================
// SMALL UTILITIES
// ============================================================
function cls(...xs) {return xs.filter(Boolean).join(" ");}

function hasYT(video) {return !!(video && window.getYouTubeId && window.getYouTubeId(video.youtube));}

function VideoTile({ video, large, onOpen }) {
  const ref = useRef(null);
  const [hover, setHover] = useState(false);
  const yt = hasYT(video);
  useEffect(() => {
    const v = ref.current;if (!v || !video.src) return;
    if (hover) {v.currentTime = 0;v.play().catch(() => {});} else {v.pause();}
  }, [hover, video.src]);

  return (
    <article
      className={cls("vt", large && "vt--lg")}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => onOpen?.(video)}>
      
      <div className="vt__media">
        {video.src ?
        <video ref={ref} src={video.src} poster={video.poster} muted playsInline loop preload="metadata" /> :
        video.poster ?
        <img className="vt__poster" src={video.poster} alt={video.title} loading="lazy" /> :

        <Placeholder label={video.category} />
        }
        <div className="vt__shade" />
        {yt &&
        <span className="vt__yt-badge" title="YouTube source">
            <svg width="12" height="9" viewBox="0 0 12 9"><path d="M0 1.5 A1.5 1.5 0 0 1 1.5 0 H10.5 A1.5 1.5 0 0 1 12 1.5 V7.5 A1.5 1.5 0 0 1 10.5 9 H1.5 A1.5 1.5 0 0 1 0 7.5 Z" fill="#ff0000" /><path d="M4.8 2.5 L8.4 4.5 L4.8 6.5 Z" fill="#fff" /></svg>
            YouTube
          </span>
        }
        <div className="vt__meta-top">
          <span className="vt__cat">{video.category}</span>
          <span className="vt__len">{video.length}</span>
        </div>
        <div className="vt__meta-bot">
          <div className="vt__play" aria-hidden="true">
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 1 L12 7 L2 13 Z" fill="currentColor" /></svg>
          </div>
          <div className="vt__title-wrap">
            <h3 className="vt__title">{video.title}</h3>
            <p className="vt__client">{video.client}</p>
          </div>
        </div>
      </div>
    </article>);

}

function Placeholder({ label }) {
  return (
    <div className="ph">
      <svg className="ph__stripes" width="100%" height="100%" preserveAspectRatio="none">
        <defs>
          <pattern id="ph-stripe" width="14" height="14" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <rect width="14" height="14" fill="transparent" />
            <line x1="0" y1="0" x2="0" y2="14" stroke="rgba(255,255,255,0.05)" strokeWidth="1" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#ph-stripe)" />
      </svg>
      <span className="ph__label">{label} · drop video here</span>
    </div>);

}

// ============================================================
// NAV
// ============================================================
function Nav({ onUpwork, onFiverr }) {
  return (
    <nav className="nav">
      <div className="nav__inner">
        <a href="#top" className="nav__logo">
          <span className="nav__mark">●</span>
          <span className="nav__name">AWAIZ</span>
          <span className="nav__sub">/ ai productions + editor</span>
        </a>
        <div className="nav__links">
          <a href="#work">Work</a>
          <a href="#post">Behind the cut</a>
          <a href="#services">Services</a>
          <a href="#about">About</a>
        </div>
        <div className="nav__cta">
          <button className="btn btn--ghost btn--sm" onClick={onFiverr}>Fiverr</button>
          <button className="btn btn--accent btn--sm" onClick={onUpwork}>Hire on Upwork →</button>
        </div>
      </div>
    </nav>);

}

// ============================================================
// HERO
// ============================================================
function Hero({ featured, onPlay, onUpwork, onFiverr }) {
  const { SplitTitle, Magnetic, Reveal } = window;
  return (
    <section className="hero" id="top" data-spotlight>
      <div className="hero__spotlight" />
      <div className="hero__grid">
        <div className="hero__copy">
          <Reveal kind="up">
            <div className="hero__tag">
              <span className="dot dot--live" /> Available · responds in ~4 hrs (PKT)
            </div>
          </Reveal>

          <SplitTitle
            as="h1"
            className="hero__title"
            text="AI productions specialist & video editor for faceless YouTube and agencies."
            accentWords={["productions", "editor"]}
            step={45} />
          

          <Reveal kind="up" delay={400}>
            <p className="hero__sub">
              You send a script and voiceover. I send back a finished video visuals built with the latest AI tools (
              <em>Veo 3.1, Kling, Seedance, Nano Banana, GPT Image 2 + more</em>),
              then cut, graded and sound-designed in Premiere Pro. Channel-ready. Not generic AI slop.
            </p>
          </Reveal>

          <Reveal kind="up" delay={500}>
            <div className="hero__cta">
              <Magnetic>
                <button className="btn btn--accent" onClick={onUpwork}>Hire on Upwork →</button>
              </Magnetic>
              <Magnetic>
                <button className="btn btn--ghost" onClick={onFiverr}>Order on Fiverr</button>
              </Magnetic>
              <a className="btn btn--text" href="#work">See the work ↓</a>
            </div>
          </Reveal>

          <Reveal kind="up" delay={600}>
            <ul className="hero__bullets">
              <li>
                <span className="hb__n">01</span>
                <span className="hb__t">Faceless storytelling, horror, documentary, ads, shorts</span>
              </li>
              <li>
                <span className="hb__n">02</span>
                <span className="hb__t">1-day turnaround for standard faceless · 2–3 days for cinematic</span>
              </li>
              <li>
                <span className="hb__n">03</span>
                <span className="hb__t">Long-form (15-20 min) and short-form (9:16) - same workflow</span>
              </li>
            </ul>
          </Reveal>
        </div>

        <Reveal kind="right" delay={200} className="hero__reel-wrap">
          <ReelPlayer video={featured} onOpen={onPlay} />
          <div className="hero__reel-meta">
            <div>
              <div className="caps">Featured</div>
              <div className="hero__reel-title">{featured?.title || "-"}</div>
            </div>
            <div className="hero__reel-tools">
              {(featured?.tools || []).slice(0, 3).map((t) => <span key={t} className="chip">{t}</span>)}
            </div>
          </div>
        </Reveal>
      </div>

      <div className="ticker">
        <div className="ticker__track">
          {Array.from({ length: 2 }).map((_, i) =>
          <span key={i} className="ticker__row">
              <span>Veo 3.1</span><i>✦</i>
              <span>Kling</span><i>✦</i>
              <span>Seedance</span><i>✦</i>
              <span>Nano Banana</span><i>✦</i>
              <span>GPT Image 2</span><i>✦</i>
              <span>Premiere Pro</span><i>✦</i>
              <span>After Effects</span><i>✦</i>
              <span>ElevenLabs</span><i>✦</i>
              <span>Lumetri grade</span><i>✦</i>
              <span>CapCut</span><i>✦</i>
              <span>Google Flow</span><i>✦</i>
            </span>
          )}
        </div>
      </div>
    </section>);

}

function ReelPlayer({ video, onOpen }) {
  const ref = useRef(null);
  const [playing, setPlaying] = useState(false);
  const yt = hasYT(video);
  const ytId = yt && window.getYouTubeId(video.youtube);
  const toggle = () => {
    if (yt) {setPlaying(true);return;}
    const v = ref.current;if (!v || !video?.src) {onOpen?.(video);return;}
    if (playing) {v.pause();} else {v.play();}
    setPlaying((p) => !p);
  };
  return (
    <div className="reel" onClick={toggle}>
      {ytId && playing ?
      <iframe
        src={`https://www.youtube.com/embed/${ytId}?autoplay=1&rel=0&modestbranding=1`}
        title={video.title}
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowFullScreen
        className="reel__yt" /> :

      video?.src ?
      <video ref={ref} src={video.src} poster={video.poster} playsInline loop preload="metadata" /> :
      video?.poster ?
      <img src={video.poster} alt={video.title} className="reel__poster" /> :

      <Placeholder label="Featured reel" />
      }
      {!playing &&
      <div className="reel__overlay">
        <div className="reel__play">
          <svg width="16" height="16" viewBox="0 0 16 16"><path d="M3 1.5 L14 8 L3 14.5 Z" fill="currentColor" /></svg>
        </div>
      </div>
      }
      <div className="reel__scan" />
    </div>);

}

// ============================================================
// WORK GRID
// ============================================================
function WorkSection({ videos, onOpen }) {
  const { Reveal } = window;
  const cats = useMemo(() => {
    const set = new Set(videos.map((v) => v.category));
    return ["All", ...set];
  }, [videos]);
  const [active, setActive] = useState("All");
  const filtered = active === "All" ? videos : videos.filter((v) => v.category === active);

  return (
    <section className="work" id="work">
      <div className="section-head">
        <div className="caps">Selected work</div>
        <h2 className="section-title">Stuff that's <em>shipped</em>.</h2>
        <p className="section-sub">Mix of client work and spec pieces. Hover to preview. Tap to open.</p>
      </div>

      <Reveal>
        <div className="filters">
          {cats.map((c) =>
          <button key={c} className={cls("filter", active === c && "filter--on")} onClick={() => setActive(c)}>
              {c}
              <span className="filter__count">
                {c === "All" ? videos.length : videos.filter((v) => v.category === c).length}
              </span>
            </button>
          )}
        </div>
      </Reveal>

      <div className="grid">
        {filtered.map((v, i) =>
        <Reveal key={v.id} kind="up" delay={i % 6 * 60}>
            <VideoTile video={v} large={i === 0 && active === "All"} onOpen={onOpen} />
          </Reveal>
        )}
      </div>
    </section>);

}

// ============================================================
// SERVICES / PRICING
// ============================================================
const SERVICES = [
{
  tier: "Standard",
  name: "Faceless AI Video",
  price: "$15-25",
  unit: "per video",
  turnaround: "~1 day",
  desc: "Ready-to-upload faceless YouTube video from your script + voiceover. Best for videos that do not require a recurring character.",
  includes: [
  "No character consistency required",
  "AI b-roll (Veo, Kling, Seedance - whatever fits)",
  "Cuts, pacing, transitions in Premiere",
  "Color grade, sound mix, captions",
  "1 revision included"]

},
{
  tier: "Cinematic",
  name: "Character-Consistent Film",
  price: "$35-50",
  unit: "per video",
  turnaround: "2-3 days",
  desc: "Storytelling, horror, documentary, or cinematic short with consistent characters across shots.",
  includes: [
  "Character sheets (Nano Banana + GPT Image 2)",
  "Shot-by-shot prompt design",
  "Cinematic color grade",
  "2 revisions included"],

  featured: true
},
{
  tier: "Retainer",
  name: "Monthly Channel Production",
  price: "$275-350",
  unit: "per month",
  turnaround: "4-8 videos / mo",
  desc: "Long-term partnership for one channel. Predictable output, predictable price, you focus on growth.",
  includes: [
  "Slack/WhatsApp comms",
  "Locked weekly schedule",
  "Priority queue",
  "Unlimited revisions included"]

}];

function Services({ onUpwork }) {
  const { Reveal } = window;
  return (
    <section className="services" id="services">
      <div className="section-head">
        <div className="caps">Services &amp; pricing</div>
        <h2 className="section-title">Three ways to <em>hire me</em>.</h2>
      </div>
      <div className="services__grid">
        {SERVICES.map((s, i) =>
        <Reveal key={s.tier} delay={i * 100}>
            <div className={cls("svc", s.featured && "svc--featured")}>
              <div className="svc__top">
                <div className="caps">{s.tier}</div>
                <h3 className="svc__name">{s.name}</h3>
                <p className="svc__desc">{s.desc}</p>
              </div>
              <div className="svc__price">
                <span className="svc__price-num">{s.price}</span>
                <span className="svc__price-unit">{s.unit}</span>
              </div>
              <div className="svc__row"><span className="caps">Turnaround</span><span>{s.turnaround}</span></div>
              <ul className="svc__list">
                {s.includes.map((i) => <li key={i}>{i}</li>)}
              </ul>
              <button className="btn btn--block" onClick={onUpwork}>Start →</button>
            </div>
          </Reveal>
        )}
      </div>
    </section>);

}

// ============================================================
// ABOUT
// ============================================================
function About() {
  const { Reveal, Counter } = window;
  return (
    <section className="about" id="about">
      <div className="about__grid">
        <div className="about__copy">
          <Reveal><div className="caps">About</div></Reveal>
          <Reveal delay={100}>
            <h2 className="section-title">I make AI video that <em>doesn't look like AI video.</em></h2>
          </Reveal>
          <Reveal delay={200}>
            <p>
              I'm Awaiz - 22, based in Pakistan, working out of hours that overlap cleanly with US daytime
              and UK evenings. I've spent years inside Premiere Pro; the AI tooling is what made it
              possible to deliver cinematic faceless content at the speed YouTube automation channels need.
            </p>
          </Reveal>
          <Reveal delay={300}>
            <p>
              The mistake most people make with AI video is treating it like a one-button replacement
              for editing. It's not. <em>Generation is 30% of the job</em> - assembly, pacing,
              sound design, and grade are the other 70%. I deliver finished files, not raw clips you
              have to fix yourself.
            </p>
          </Reveal>
          <Reveal delay={400}>
            <div className="about__stats">
              <div>
                <span className="about__num"><Counter to={15} suffix="h" /></span>
                <span className="caps">/ day capacity</span>
              </div>
              <div>
                <span className="about__num">~<Counter to={24} suffix="h" /></span>
                <span className="caps">/ standard turnaround</span>
              </div>
              <div>
                <span className="about__num">10pm–4am</span>
                <span className="caps">PKT peak hours</span>
              </div>
            </div>
          </Reveal>
        </div>
        <div className="about__side">
          <Reveal delay={150}>
            <div className="card">
              <div className="caps">Tools I run daily</div>
              <div className="tools">
                {["Adobe Premiere Pro", "After Effects", "Lumetri", "Veo 3.1", "Kling", "Seedance", "Nano Banana", "GPT Image 2", "Google Flow", "ElevenLabs", "CapCut", "ChatGPT", "Claude"].map((t) =>
                <span key={t} className="chip chip--lg">{t}</span>
                )}
              </div>
            </div>
          </Reveal>
          <Reveal delay={250}>
            <div className="card">
              <div className="caps">Best fit clients</div>
              <ul className="bullets">
                <li>YouTube automation / faceless channels</li>
                <li>Horror, storytelling, documentary niches</li>
                <li>Agencies needing white-label AI video</li>
                <li>Founders who want a monthly retainer, not one-offs</li>
              </ul>
            </div>
          </Reveal>
          <Reveal delay={350}>
            <div className="card card--mute">
              <div className="caps">Won't take on</div>
              <ul className="bullets bullets--mute">
                <li>Unclear scripts or no script at all</li>
                <li>"Hollywood quality for $20"</li>
                <li>Unlimited revisions</li>
                <li>Religious dialogue or suggestive content</li>
              </ul>
            </div>
          </Reveal>
        </div>
      </div>
    </section>);

}

// ============================================================
// CTA
// ============================================================
function CTA({ onUpwork, onFiverr }) {
  const { Reveal, Magnetic } = window;
  const gmailCompose = "https://mail.google.com/mail/?view=cm&fs=1&to=aastudio.bn@gmail.com";
  return (
    <section className="cta">
      <div className="cta__inner">
        <Reveal><div className="caps">Next step</div></Reveal>
        <Reveal delay={100}>
          <h2 className="cta__title">Got a script and a voiceover? <em>Send it.</em></h2>
        </Reveal>
        <Reveal delay={200}>
          <p className="cta__sub">First reply usually within a few hours. Quote within the same day.</p>
        </Reveal>
        <Reveal delay={300}>
          <div className="cta__row">
            <Magnetic>
              <button className="btn btn--accent btn--lg" onClick={onUpwork}>Hire on Upwork →</button>
            </Magnetic>
            <Magnetic>
              <button className="btn btn--ghost btn--lg" onClick={onFiverr}>Order on Fiverr</button>
            </Magnetic>
            <a className="btn btn--text btn--lg" href={gmailCompose} target="_blank" rel="noopener noreferrer">Email a brief</a>
          </div>
        </Reveal>
      </div>
    </section>);

}

// ============================================================
// FOOTER
// ============================================================
function Footer({ onUpwork, onFiverr }) {
  const gmailCompose = "https://mail.google.com/mail/?view=cm&fs=1&to=aastudio.bn@gmail.com";
  return (
    <footer className="footer">
      <div className="footer__row">
        <div>
          <div className="nav__logo nav__logo--big">
            <span className="nav__mark">●</span>
            <span className="nav__name">AWAIZ</span>
          </div>
          <p className="footer__line">AI Productions + Video Editor · Pakistan · UTC+5</p>
        </div>
        <div className="footer__cols">
          <div>
            <div className="caps">Hire</div>
            <a href="#" onClick={(e) => {e.preventDefault();onUpwork();}} className="footer__link">Upwork profile</a>
            <a href="#" onClick={(e) => {e.preventDefault();onFiverr();}} className="footer__link">Fiverr gig</a>
            <a href={gmailCompose} target="_blank" rel="noopener noreferrer" className="footer__link">Email</a>
          </div>
          <div>
            <div className="caps">Social</div>
            <a href="#" className="footer__link">Instagram</a>
            <a href="#" className="footer__link">YouTube</a>
          </div>
        </div>
      </div>
      <div className="footer__base">
        <span>© 2025 Awaiz</span>
        <span>Made fast. Shipped faster.</span>
      </div>
    </footer>);

}

// ============================================================
// LIGHTBOX
// ============================================================
function Lightbox({ video, onClose }) {
  useEffect(() => {
    if (!video) return;
    const onKey = (e) => {if (e.key === "Escape") onClose();};
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {window.removeEventListener("keydown", onKey);document.body.style.overflow = "";};
  }, [video, onClose]);
  if (!video) return null;
  const ytId = window.getYouTubeId && window.getYouTubeId(video.youtube);
  return (
    <div className="lb" onClick={onClose}>
      <div className="lb__inner" onClick={(e) => e.stopPropagation()}>
        <button className="lb__close" onClick={onClose}>Close ×</button>
        <div className="lb__media">
          {ytId ?
          <iframe
            src={`https://www.youtube.com/embed/${ytId}?autoplay=1&rel=0&modestbranding=1`}
            title={video.title}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            frameBorder="0"
            className="lb__yt" /> :

          video.src ?
          <video src={video.src} poster={video.poster} controls autoPlay playsInline /> :

          <Placeholder label={video.category} />
          }
        </div>
        <div className="lb__meta">
          <div className="caps">{video.category} · {video.length} · {video.year}</div>
          <h3 className="lb__title">{video.title}</h3>
          <p className="lb__client">{video.client}</p>
          <p className="lb__desc">{video.description}</p>
          <div className="tools">
            {(video.tools || []).map((t) => <span key={t} className="chip">{t}</span>)}
          </div>
        </div>
      </div>
    </div>);

}

// ============================================================
// APP
// ============================================================
function App() {
  const [t, setTweak] = window.useTweaks(window.TWEAK_DEFAULTS);
  const palette = PALETTES[t.palette] || PALETTES.amber;

  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty("--accent", palette.accent);
    r.style.setProperty("--accent-soft", palette.accentSoft);
    r.style.setProperty("--accent-deep", palette.accentDeep);
    r.dataset.density = t.density;
    r.dataset.layout = t.heroLayout;
  }, [t.palette, t.density, t.heroLayout]);

  const videos = window.VIDEOS || [];
  const featured = window.HERO_VIDEO || videos.find((v) => v.featured) || videos[0];
  const [open, setOpen] = useState(null);
  const onUpwork = () => window.open(window.UPWORK_URL || "#", "_blank");
  const onFiverr = () => window.open(window.FIVERR_URL || "#", "_blank");

  return (
    <>
      <window.ScrollProgress />
      <window.Spotlight selector="[data-spotlight]" />
      <Nav onUpwork={onUpwork} onFiverr={onFiverr} />
      <Hero featured={featured} onPlay={setOpen} onUpwork={onUpwork} onFiverr={onFiverr} />
      <WorkSection videos={videos} onOpen={setOpen} />
      <window.Postproduction />
      <window.ColorGrade />
      <window.Pipeline />
      <Services onUpwork={onUpwork} />
      <About />
      <CTA onUpwork={onUpwork} onFiverr={onFiverr} />
      <Footer onUpwork={onUpwork} onFiverr={onFiverr} />
      <Lightbox video={open} onClose={() => setOpen(null)} />

      {window.TweaksPanel &&
      <window.TweaksPanel title="Tweaks">
          <window.TweakSection label="Accent">
            <window.TweakColor
            label="Palette"
            value={PALETTES[t.palette].accent}
            options={Object.values(PALETTES).map((p) => p.accent)}
            onChange={(hex) => {
              const key = Object.keys(PALETTES).find((k) => PALETTES[k].accent === hex);
              if (key) setTweak("palette", key);
            }} />
          
          </window.TweakSection>
          <window.TweakSection label="Density">
            <window.TweakRadio
            label="Spacing"
            value={t.density}
            options={["compact", "relaxed"]}
            onChange={(v) => setTweak("density", v)} />
          
          </window.TweakSection>
          <window.TweakSection label="Hero layout">
            <window.TweakRadio
            label="Layout"
            value={t.heroLayout}
            options={["split", "stack"]}
            onChange={(v) => setTweak("heroLayout", v)} />
          
          </window.TweakSection>
        </window.TweaksPanel>
      }
    </>);

}

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