const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "variant": "a",
  "accentHue": "burnt",
  "showSticky": true,
  "headlineMode": "bedtime"
}/*EDITMODE-END*/;

const CONTACT_EMAIL = "howdy@dadrepreneurs.com";

const HEADLINES = {
  alright:    { pre: "EVERYTHING", em: "is alright.", post: "" },
  figuring:   { pre: "WE'RE FIGURING IT OUT", em: "as we go.", post: "JUST LIKE YOU." },
  bedtime:    { pre: "BETWEEN BEDTIME STORIES", em: "&", post: "BALANCE SHEETS." },
};

const ACCENTS = {
  burnt:   "#c95a2c",
  moss:    "#5b7a4d",
  leather: "#9a6a3f",
  slate:   "#2c3e50",
};

const EPISODES = [
  {
    n: "001", date: "COMING SOON", runtime: "TRAILER",
    title: "What is a Dadrepreneur?",
    desc: "The opening conversation on ambition, family, business, and why pretending to have it all figured out is exhausting.",
    guest: "with Jon-Mark Craddock & Jon Blair", tags: ["Founder Stories", "Modern Fatherhood"],
  },
  {
    n: "002", date: "COMING SOON", runtime: "DRAFT",
    title: "Calendars tell the truth",
    desc: "A practical look at what our schedules reveal about work, home, priorities, and the stories we tell ourselves.",
    guest: "with Jon-Mark Craddock & Jon Blair", tags: ["Time Management", "Systems & Sanity"],
  },
  {
    n: "003", date: "COMING SOON", runtime: "DRAFT",
    title: "Cash, kids, and keeping promises",
    desc: "The very real overlap between business decisions, family margin, and the cost of saying yes to too much.",
    guest: "with Jon-Mark Craddock & Jon Blair", tags: ["Money & Finance", "Marriage & Family"],
  },
];

const QUOTES = [
  { text: "You are building something real, but you still want to be there for bedtime.", who: "For", role: "Founder dads" },
  { text: "You like business wisdom better when it sounds like a normal human said it.", who: "For", role: "Operators" },
  { text: "You are ambitious, tired, grateful, and occasionally remembering to take the trash out.", who: "For", role: "The rest of us" },
];

function Util() {
  return (
    <div className="util">
      <div className="util-inner">
        <div><span className="dot"></span>LAUNCHING SOON</div>
        <div>RECORDED IN THE TEXAS HILL COUNTRY</div>
      </div>
    </div>
  );
}

function Nav() {
  return (
    <nav className="top">
      <div className="nav-inner">
        <a className="brand" href="#" aria-label="The Dadrepreneur Podcast home">
          <img className="brand-wordmark" src="assets/dadrepreneur-wordmark.svg" alt="The Dadrepreneur Podcast" />
        </a>
        <div className="nav-links">
          <a href="#" className="active">Home</a>
          <a href="#contact">Contact</a>
        </div>
        <div className="nav-cta">
          <a className="btn small" href="#contact">Contact <span className="arrow">→</span></a>
        </div>
      </div>
    </nav>
  );
}

function VariationBar({ variant, setVariant }) {
  const items = [
    { k: "a", l: "Editorial" },
    { k: "b", l: "Magazine" },
    { k: "c", l: "Late-night" },
  ];
  return (
    <div className="variation-bar">
      <span className="lbl">Hero Variation</span>
      {items.map(i => (
        <button key={i.k} className={variant === i.k ? "active" : ""} onClick={() => setVariant(i.k)}>{i.l}</button>
      ))}
    </div>
  );
}

function HeroHeadline({ mode }) {
  const h = HEADLINES[mode] || HEADLINES.alright;
  return (
    <h1>
      {h.pre}{h.pre && " "}
      <span className="it">{h.em}</span>
      {h.post && <><br/>{h.post}</>}
    </h1>
  );
}

function HeroArt({ variant }) {
  return (
    <div className="hero-art brand-hero-art">
      <span className="tag">EP. 001 · COMING SOON</span>
      <img className="mug-art" src="assets/dadrepreneur-mug.svg" alt="The Dadrepreneur Podcast coffee mug" />
      <span className="stamp">Recorded in the Texas Hill Country</span>
    </div>
  );
}

function Hero({ variant, headlineMode, onPlay }) {
  return (
    <section className="hero" data-variant={variant}>
      <div className="hero-inner">
        <div className="eyebrow">
          <span className="bar"></span>
          <span>A PODCAST FOR DADS WHO DO BOTH</span>
          <span className="live">● SEASON 01</span>
        </div>
        <div className="hero-grid">
          <div>
            <HeroHeadline mode={headlineMode} />
            <p className="lede">
              Real conversations with dads building businesses, raising families, and trying
              to keep the wheels from falling off. No hustle culture. No guru nonsense.
              Just two guys in the trenches — enjoying it.
            </p>
            <div className="hero-actions">
              <button className="btn" onClick={onPlay}>
                ▸ Listen Now <span className="arrow">→</span>
              </button>
              <a className="btn ghost" href="#newsletter">Subscribe</a>
            </div>
            <div className="hero-stats">
              <div className="s"><span className="n">3</span><span className="t">Launch episodes</span></div>
              <div className="s"><span className="n">2</span><span className="t">Dads</span></div>
              <div className="s"><span className="n">5</span><span className="t">Kids</span></div>
              <div className="s"><span className="n">1</span><span className="t">Honest show</span></div>
            </div>
          </div>
          <HeroArt variant={variant} />
        </div>
      </div>
    </section>
  );
}

function Marquee() {
  const items = ["GROUNDED AMBITION", "MODERN FATHERHOOD", "REAL CONVERSATIONS", "FAMILY-FIRST ENTREPRENEURSHIP", "HONEST HUMOR", "USEFUL BUSINESS WISDOM"];
  const row = (
    <span>
      {items.map((t,i)=>(
        <React.Fragment key={i}>
          {t}<span className="star">  ✦  </span>
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div className="marquee">
      <div className="marquee-track">
        {row}{row}{row}{row}
      </div>
    </div>
  );
}

function Player({ episode, isPlaying, onToggle }) {
  return (
    <div className="player">
      <button className={"play " + (isPlaying ? "playing" : "")} onClick={onToggle} aria-label={isPlaying ? "Pause" : "Play"}>
        <svg className="tri" viewBox="0 0 24 24"><path d="M6 4l14 8-14 8z"/></svg>
        <svg className="pause" viewBox="0 0 24 24"><path d="M6 4h4v16H6zM14 4h4v16h-4z" fill="currentColor"/></svg>
      </button>
      <div className="player-mid">
        <div className="player-meta">
          <span className="ttl">EP. {episode.n} · {episode.title.slice(0,46)}…</span>
          <span>18:42 / {episode.runtime}</span>
        </div>
        <div className="scrub"><div className="fill"></div><div className="knob"></div></div>
      </div>
      <div className="player-right">
        <button className="icon" aria-label="Back 15"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg></button>
        <button className="icon" aria-label="Fwd 30"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 4v5h-5"/></svg></button>
      </div>
    </div>
  );
}

function FeaturedEpisode({ isPlaying, onToggle }) {
  const ep = EPISODES[0];
  return (
    <section className="wrap">
      <div className="section-head">
        <h2>The featured one.</h2>
        <div className="meta"><span className="num">01</span><span className="mono">FEATURED EPISODE</span></div>
      </div>
      <div className="featured-grid">
        <div className="feat-art">
          <span className="num">{ep.n}</span>
          <span className="tag">FEATURED</span>
          <div className="stripes"></div>
          <div className="blob"></div>
          <div className="blob2"></div>
          <span className="runtime">{ep.runtime} · {ep.date}</span>
        </div>
        <div>
          <div className="feat-meta">
            {ep.tags.map(t => <span className="pill" key={t}>{t}</span>)}
            <span style={{color:"var(--muted)", fontSize:13, letterSpacing:"0.1em", textTransform:"uppercase"}}>{ep.guest}</span>
          </div>
          <h3 className="feat-title">{ep.title}</h3>
          <p className="feat-desc">
            The starting point for the whole show: what it means to build companies and families
            at the same time without turning life into a hustle-culture bumper sticker.
          </p>
          <div className="feat-takeaways">
            <div className="ta"><span className="n">01</span><div><strong>Cash beats clever.</strong> Six months runway is a marriage benefit.</div></div>
            <div className="ta"><span className="n">02</span><div><strong>Calendar tells the truth.</strong> Look at last week — not last year.</div></div>
            <div className="ta"><span className="n">03</span><div><strong>"The talk" before the crisis.</strong> Saves the talk during it.</div></div>
            <div className="ta"><span className="n">04</span><div><strong>Boring systems, free weekends.</strong> Pick the boring one. Always.</div></div>
          </div>
          <Player episode={ep} isPlaying={isPlaying} onToggle={onToggle} />
        </div>
      </div>
    </section>
  );
}

function RecentEpisodes({ onPlay }) {
  return (
    <section className="wrap recent">
      <div className="section-head">
        <h2>Recently in the room.</h2>
      </div>
      <div className="recent-list">
        {EPISODES.map((ep) => (
          <div className="ep" key={ep.n}>
            <div className="epnum">{ep.n}</div>
            <div className="epart"><div className="c1"></div><div className="c2"></div></div>
            <div>
              <div className="ep-title">{ep.title}</div>
              <div className="ep-desc">{ep.desc}</div>
              <div className="ep-tags">
                {ep.tags.map(t => <span className="pill" key={t}>{t}</span>)}
              </div>
            </div>
            <div className="ep-runtime">{ep.runtime}<br/><span style={{opacity:.7}}>{ep.date}</span></div>
            <button className="ep-play" onClick={onPlay} aria-label="Play episode">
              <svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 4l14 8-14 8z"/></svg>
            </button>
          </div>
        ))}
      </div>
    </section>
  );
}

function WhatThisIs() {
  const items = [
    { n: "01", t: "Real conversations.", d: "Two guys, no script, occasional tangents about pickup trucks." },
    { n: "02", t: "Useful, not preachy.", d: "If we don't use it Monday morning, it doesn't make the cut." },
    { n: "03", t: "Family-first ambition.", d: "We celebrate the work without pretending the kids don't exist." },
    { n: "04", t: "Honest humor.", d: "Because none of us have it figured out, and the alternative is grim." },
  ];
  return (
    <section className="wrap what">
      <div className="what-grid">
        <div>
          <div className="mono" style={{color:"var(--muted)", marginBottom:14}}>— WHAT THIS IS</div>
          <h2>A podcast for dads<br/>who do <span className="it">both.</span></h2>
        </div>
        <div>
          <p>
            We're not interested in pretending. Between us, we have five kids,
            two very patient wives, several businesses, plenty of spreadsheets,
            a few late nights, and just enough optimism to start a podcast about all of it.
          </p>
          <p>
            This is the show we wish we had on the drive home — the kind of conversation
            you'd have with a friend who's a few steps ahead, or a few steps behind,
            but on the same road.
          </p>
          <ul className="what-list">
            {items.map(i => (
              <li key={i.n}>
                <span className="num">{i.n}</span>
                <div>
                  <div className="ttl">{i.t}</div>
                  <div className="desc">{i.d}</div>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

function Hosts() {
  return (
    <section className="wrap hosts">
      <div className="hosts-head">
        <div>
          <div className="mono" style={{color:"var(--muted)", marginBottom:10}}>— THE HOSTS</div>
          <h2>Two dads. <span className="it">Two desks.</span><br/>Two very patient wives.</h2>
        </div>

      </div>
      <div className="hosts-grid">
        <article className="host">
          <div className="host-portrait h1 has-photo">
            <div className="bg"></div>
            <img className="host-photo" src="assets/jon-mark-family.jpg" alt="Jon-Mark Craddock family photo" />
            <span className="label">HOST · 01</span>
          </div>
          <div className="host-body">
            <div className="host-name">Jon-Mark Craddock</div>
            <div className="host-role">Owner & CEO, La Matera</div>
            <p className="host-bio">
              Five years into a one-year DIY house renovation. Father of two. Abides outside of Austin in the TX Hill Country.
              Married to a woman who is, statistically, way more patient than he deserves.
            </p>
            <div className="host-meta">
              <div className="it"><strong>Kids</strong><span>2</span></div>
              <div className="it"><strong>Cos.</strong><span>2</span></div>
              <div className="it"><strong>HQ</strong><span>Spicewood, TX</span></div>
            </div>
          </div>
        </article>
        <article className="host">
          <div className="host-portrait h2 has-photo">
            <div className="bg"></div>
            <img className="host-photo" src="assets/jon-blair-family.jpg" alt="Jon Blair family photo" />
            <span className="label">HOST · 02</span>
          </div>
          <div className="host-body">
            <div className="host-name">Jon Blair</div>
            <div className="host-role">Founder, Free To Grow CFO</div>
            <p className="host-bio">
              Former CFO/COO at Guardian Bikes — helped grow it from $0 to 8 figures and raise $15MM+.
              Father of three. Real estate on the side. Jon and his four roommates call Lakeway, TX home. Same kind of patient wife.
            </p>
            <div className="host-meta">
              <div className="it"><strong>Kids</strong><span>3</span></div>
              <div className="it"><strong>Cos.</strong><span>3</span></div>
              <div className="it"><strong>HQ</strong><span>Austin, TX</span></div>
            </div>
          </div>
        </article>
      </div>
    </section>
  );
}

function Quotes() {
  return (
    <section className="quotes">
      <div className="wrap">
        <div className="section-head" style={{borderColor:"var(--ink)"}}>
          <h2>Who this is for.</h2>
          <span className="mono" style={{color:"var(--muted)"}}>— AUDIENCE NOTES</span>
        </div>
        <div className="quotes-grid" style={{paddingTop:32}}>
          {QUOTES.map((q,i) => (
            <div className="quote" key={i}>
              <div className="qmark">"</div>
              <p>{q.text}</p>
              <div className="who">
                <span className="name">{q.who}</span>
                <span className="role">{q.role}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Newsletter() {
  const [sent, setSent] = useState(false);
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("");

  const submitEmail = async (e) => {
    e.preventDefault();
    if (!email) return;
    setStatus("Saving...");
    try {
      const res = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, source: "Dadrepreneur website" })
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || "Could not save email yet.");
      setSent(true);
      setStatus("");
    } catch (err) {
      setStatus("Signup is almost ready. For now, email us at howdy@dadrepreneurs.com and we'll add you manually.");
    }
  };

  return (
    <section className="newsletter" id="newsletter">
      <div className="wrap news-inner">
        <div>
          <div className="mono" style={{color:"var(--tan)", marginBottom:14}}>— THE WEEKLY DADPRENEUR PLAYBOOK</div>
          <h2>One email.<br/><span className="it">Tuesday morning.</span><br/>Worth the inbox real estate.</h2>
          <p className="sub">A short weekly note for dads building businesses, raising families, and trying to make better decisions with fewer hours in the day.</p>
          <ul className="promise">
            <li>One business idea worth stealing</li>
            <li>One fatherhood thought worth chewing on</li>
            <li>One practical takeaway worth doing Monday</li>
            <li>One thing worth reading, watching, or fixing this week</li>
          </ul>
        </div>
        <form className={"news-form" + (sent ? " sent" : "")} onSubmit={submitEmail}>
          <div className="label">Join the list — Tuesdays only</div>
          <div className="field">
            <input type="email" placeholder="you@yourdomain.com" value={email} onChange={e=>setEmail(e.target.value)} required />
            <button type="submit" className="submit">Join →</button>
          </div>
          <div className="success">★ You're in. First one lands Tuesday.</div>
          {status && <div className="form-status">{status}</div>}
          <div className="fine">No spam. No "course" upsell. No 47-tweet threads.</div>
        </form>
      </div>
    </section>
  );
}

function Contact() {
  return (
    <section className="contact" id="contact">
      <div className="wrap contact-inner">
        <div>
          <div className="mono" style={{color:"var(--muted)", marginBottom:12}}>— CONTACT</div>
          <h2>Howdy.</h2>
          <p>For guests, sponsorships, questions, or Hill Country dad-business stories, send us a note.</p>
        </div>
        <a className="btn" href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL} <span className="arrow">→</span></a>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <div className="wrap footer-grid single-footer">
        <div className="foot-brand">
          <img className="footer-wordmark" src="assets/dadrepreneur-wordmark.svg" alt="The Dadrepreneur Podcast" />
          <p>Where fatherhood meets entrepreneurship. New episodes every Tuesday morning, recorded in the Texas Hill Country.</p>
        </div>
        <div className="foot-col footer-contact">
          <h4>Contact</h4>
          <ul>
            <li><a href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL}</a></li>
          </ul>
        </div>
      </div>
      <div className="wrap foot-bottom">
        <span>© The Dadrepreneur Podcast · Recorded in the Texas Hill Country</span>
        <span>Built between bedtime stories & balance sheets</span>
      </div>
    </footer>
  );
}

function StickyPlayer({ show, isPlaying, onToggle, onClose }) {
  return (
    <div className={"stickyplayer" + (show ? " show" : "")}>
      <div className="sp-inner">
        <div className="sp-art"><div className="c"></div><div className="c2"></div></div>
        <button className={"sp-play " + (isPlaying ? "playing" : "")} onClick={onToggle} aria-label="Play/Pause">
          <svg className="tri" viewBox="0 0 24 24"><path d="M6 4l14 8-14 8z"/></svg>
          <svg className="pause" viewBox="0 0 24 24"><path d="M6 4h4v16H6zM14 4h4v16h-4z" fill="currentColor"/></svg>
        </button>
        <div className="sp-meta">
          <div className="sp-title">EP. 001 — What is a Dadrepreneur?</div>
          <div className="sp-scrub"><div className="fill" id="sp-fill"></div></div>
        </div>
        <div className="sp-time" id="sp-time">00:00 / 18:00</div>
        <button className="sp-close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
        </button>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = window.useTweaks
    ? window.useTweaks(TWEAK_DEFAULTS)
    : [TWEAK_DEFAULTS, () => {}];
  const [variant, setVariant] = useState(t.variant || "a");
  const [isPlaying, setPlaying] = useState(false);
  const [stickyOpen, setStickyOpen] = useState(false);
  const [progress, setProgress] = useState(0);

  useEffect(() => { setVariant(t.variant || "a"); }, [t.variant]);

  // simulate playback
  useEffect(() => {
    if (!isPlaying) return;
    const id = setInterval(() => setProgress(p => (p + 0.4) % 100), 200);
    return () => clearInterval(id);
  }, [isPlaying]);

  useEffect(() => {
    const fill = document.getElementById("sp-fill");
    const time = document.getElementById("sp-time");
    if (fill) fill.style.width = progress.toFixed(1) + "%";
    if (time) {
      const total = 18 * 60;
      const cur = Math.floor((progress/100) * total);
      const m = String(Math.floor(cur/60)).padStart(2,"0");
      const s = String(cur%60).padStart(2,"0");
      time.textContent = `${m}:${s} / 18:00`;
    }
  }, [progress]);

  const handlePlay = () => {
    setStickyOpen(true);
    setPlaying(true);
  };
  const handleToggle = () => setPlaying(p => !p);

  // expose hue via inline style
  const accent = ACCENTS[t.accentHue] || ACCENTS.burnt;
  useEffect(() => {
    document.documentElement.style.setProperty("--burnt", accent);
  }, [accent]);

  // Tweaks panel

  return (
    <>
      <Util />
      <Nav />

      <Hero variant={variant} headlineMode={t.headlineMode} onPlay={handlePlay} />
      <Marquee />
      <FeaturedEpisode isPlaying={isPlaying} onToggle={handleToggle} />
      <RecentEpisodes onPlay={handlePlay} />
      <WhatThisIs />
      <Hosts />
      <Quotes />
      <Newsletter />
      <Contact />
      <Footer />
      {t.showSticky && stickyOpen && <StickyPlayer show={stickyOpen} isPlaying={isPlaying} onToggle={handleToggle} onClose={()=>{setStickyOpen(false); setPlaying(false);}} />}

    </>
  );
}

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