// Other sections: About, Tutorials, Workshops, Tools, Contact

function BioModal({ onClose }) {
  React.useEffect(function() {
    var onKey = function(e) { if (e.key === "Escape") onClose(); };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return function() {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [onClose]);

  return (
    <div className="bio-overlay" onClick={onClose}>
      <div className="bio-modal" onClick={function(e) { e.stopPropagation(); }}>
        <header className="bio-modal-header">
          <span className="bio-modal-label">EXTENDED BIO</span>
          <button className="cs-close" onClick={onClose}><span>Close</span></button>
        </header>
        <div className="bio-modal-body">
          <img className="bio-modal-photo" src="https://MyPortfolioWebsite.b-cdn.net/static/FunctionStore_headshot_square.jpg" alt="Dan Molnar" />
          <p className="bio-modal-lead">Dan Molnar is a <strong>Berlin-based artist and developer</strong> working under the alias <strong>Function Store</strong> — merging technical fluency with a deep passion for <strong>music-inspired visuals</strong> to create audiovisual and immersive-interactive experiences.</p>
          <p>Trained in <strong>electrical engineering at Budapest University of Technology and Economics</strong>, Dan brings an unusually rigorous technical foundation to his creative practice. This background allows him to approach complex, large-scale projects with both artistic intent and engineering precision.</p>
          <p>Fuelled by a lifelong passion for <strong>music production and guitar</strong>, Dan channels sound into the visual realm — building immersive experiences that resonate on multiple sensory levels. His work spans <strong>live performance systems, permanent installations, and audiovisual art</strong>.</p>
          <p>As a <strong>system designer</strong>, he specialises in robust, high-performance <strong>TouchDesigner</strong> environments for installations — building flexible infrastructures that serve both the creative vision of visual developers and the operational needs of clients. He also develops <strong>custom tools and components</strong> used by artists at festivals and studios worldwide.</p>
          <p>Dan is co-founder of <a className="bio-modal-link" href="https://derealstudio.com" target="_blank" rel="noopener"><strong>DEREAL Studio</strong></a>, a creative studio working at the intersection of immersive technology and spatial experience.</p>
          <p>Committed to community and education, he shares long-form knowledge through <strong>YouTube and Patreon</strong>, and leads hands-on <strong>workshops</strong> for artists and developers at all levels — from first patches to touring production rigs.</p>
          <div className="bio-modal-cta">
            <a href="mailto:dan@functionstore.xyz" className="bio-modal-cta-link">
              <span>Get in touch</span>
              <span>dan@functionstore.xyz ↗</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

function About() {
  var [bioOpen, setBioOpen] = React.useState(false);
  return (
    <section className="sec sec-about" id="about">
      <SecHeader num="02" label="ABOUT" />
      {bioOpen && <BioModal onClose={function() { setBioOpen(false); }} />}
      <div className="about-grid">
        <div className="about-photo">
          <img src="https://MyPortfolioWebsite.b-cdn.net/static/FunctionStore_headshot_square.jpg" alt="Dan Molnar" />
        </div>
        <div className="about-col">
          <p className="about-lead">
            Artist and developer based in Berlin, working as <em>Function Store</em>.
          </p>
          <p className="about-body" data-cursor="READ">
            Trained in electrical engineering at Budapest University of Technology and Economics,
            Dan merges technical fluency with a deep passion for music-inspired visuals — creating
            audiovisual and immersive-interactive experiences that bridge art and technology.
          </p>
          <p className="about-body" data-cursor="READ">
            As a system designer, he builds robust, high-performance TouchDesigner environments
            for installations, tailored to the needs of clients and the creative vision of visual
            developers. He also develops custom tools and components used by artists worldwide.
            He is co-founder of <a className="about-inline-link" href="https://derealstudio.com" target="_blank" rel="noopener">DEREAL Studio</a>.
          </p>
          <p className="about-body" data-cursor="READ">
            Dan shares his knowledge through long-form tutorials on YouTube and Patreon, and runs
            hands-on workshops for artists and developers at all levels.
          </p>
          <button className="about-bio-btn" onClick={function() { setBioOpen(true); }} data-cursor="READ">
            <span>Full bio</span>
            <span className="about-bio-arrow">↗</span>
          </button>
        </div>
        <div className="about-col about-meta">
          <MetaBlock label="Based" value="Berlin, DE" idx={1} />
          <MetaBlock label="Origin" value="Budapest, HU" idx={2} />
          <MetaBlock label="Education" value="Electrical Engineering — BME Budapest" idx={3} span />
          <MetaBlock label="Stack" tags value={["TouchDesigner", "Python", "Guitar"]} idx={4} />
          <MetaBlock label="Practice" value={["Audiovisual installation", "Immersive-interactive", "System design", "TD tools & components", "Workshops & education"]} idx={5} span />
          <MetaBlock label="For hire" value={["Commissions", "Workshops and talks", "Collaborations", "Consulting"]} idx={6} span />
          <MetaBlock label="Languages" value="Hungarian · English" idx={7} />
          <MetaBlock label="Studio" value="DEREAL Studio" link="https://derealstudio.com" idx={8} />
        </div>
      </div>
    </section>
  );
}

function MetaBlock({ label, value, idx, tags, link, span }) {
  var items = Array.isArray(value) ? value : [value];
  return (
    <div className={"meta-block" + (span ? " meta-block--span" : "")}>
      {idx && <div className="meta-idx">{String(idx).padStart(2, "0")}</div>}
      <div className="meta-label">{label}</div>
      {tags ? (
        <div className="meta-value meta-value--tags">
          {items.map(function(tag) {
            return <span key={tag} className="stack-tag">{tag}</span>;
          })}
        </div>
      ) : items.length > 1 ? (
        <ul className="meta-list">
          {items.map(function(item, i) {
            return <li key={i} className="meta-list-item">{item}</li>;
          })}
        </ul>
      ) : link ? (
        <a className="meta-value meta-value--link" href={link} target="_blank" rel="noopener">
          {items[0]}<span className="meta-value-arrow">↗</span>
        </a>
      ) : (
        <div className="meta-value">{items[0]}</div>
      )}
    </div>
  );
}

function Tutorials() {
  return (
    <section className="sec sec-tut" id="tutorials">
      <SecHeader num="03" label="TUTORIALS & EDUCATION" />
      <div className="tut-intro">
        <p>Long-form video on YouTube and Patreon. 700k+ followers across platforms.</p>
        <div className="tut-platforms">
          <a className="tut-plat" data-cursor="WATCH ↗">
            <span>YOUTUBE</span><span>↗</span>
          </a>
          <a className="tut-plat" data-cursor="SUPPORT ↗">
            <span>PATREON</span><span>↗</span>
          </a>
        </div>
      </div>
      <div className="tut-list">
        {window.TUTORIALS.map(function(t, i) {
          var platformClass = t.platform === "YouTube" ? "tut-platform tut-platform-yt" : "tut-platform tut-platform-pt";
          return (
            <div key={i} className="tut-row" data-cursor="WATCH">
              <span className="tut-idx">{String(i + 1).padStart(2, "0")}</span>
              <span className="tut-title">{t.title}</span>
              <span className={platformClass}>{t.platform.toUpperCase()}</span>
              <span className="tut-views">{t.views}</span>
              <span className="tut-dur">{t.duration}</span>
              <span className="tut-year">{t.year}</span>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function Workshops({ onOpen }) {
  var today = new Date();
  var TYPE_GLYPH = { Workshop: "◈", Talk: "◎", Interview: "◇" };

  var sorted = (window.WORKSHOPS || []).slice().sort(function(a, b) {
    var da = new Date(a.date), db = new Date(b.date);
    var af = da > today, bf = db > today;
    if (af && !bf) return -1;
    if (!af && bf) return 1;
    return af ? da - db : db - da;
  });

  var hasUpcoming = sorted.length > 0 && new Date(sorted[0].date) > today;

  function WsCard({ w }) {
    var d = new Date(w.date);
    var future = d > today;
    var mon = d.toLocaleString("en", { month: "short" });
    var year = d.getFullYear();
    var glyph = TYPE_GLYPH[w.type] || "◇";
    var relProjects = (w.relatedProjects || []).map(function(pid) {
      return (window.PROJECTS || []).find(function(p) { return p.id === pid; });
    }).filter(Boolean);

    return (
      <div className={"ws-card ws-card--" + w.type.toLowerCase() + (future ? " ws-card--upcoming" : "")}>
        <a className="ws-card-link" href={w.link} target="_blank" rel="noopener">
          <div className="ws-card-media">
            <div className="ws-card-bg"></div>
            <div className="ws-card-glyph">{glyph}</div>
            {future && <span className="ws-card-badge">UPCOMING</span>}
            <div className="pcard-brackets">
              <span className="pcb pcb-tl"></span><span className="pcb pcb-tr"></span>
              <span className="pcb pcb-bl"></span><span className="pcb pcb-br"></span>
            </div>
            <div className="ws-card-overlay">
              <span className="ws-card-date">{future ? "Upcoming" : mon + " " + year}</span>
              <span className="ws-card-ext">↗ {w.format}</span>
            </div>
            <div className="pcard-hover-line"></div>
          </div>
          <div className="pcard-info">
            <span className="pcard-title">{w.title}</span>
            <div className="pcard-meta">
              <span className="pcard-client">{w.event}</span>
              <span className="pcard-year">{w.type}</span>
            </div>
          </div>
        </a>
        {relProjects.length > 0 && (
          <div className="ws-rel">
            <span className="ws-rel-label">Related work</span>
            {relProjects.map(function(p) {
              return (
                <button key={p.id} className="ws-rel-item" onClick={function() { if (onOpen) onOpen(p); }}>
                  {p.posterUrl && <img className="ws-rel-thumb" src={p.posterUrl} alt={p.title} />}
                  <span className="ws-rel-title">{p.title}</span>
                  <span className="ws-rel-arrow">→</span>
                </button>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  return (
    <section className="sec sec-workshops" id="workshops">
      <SecHeader num="04" label="WORKSHOPS &amp; TALKS" />
      {!hasUpcoming && (
        <div className="ws-none">No upcoming events — check back soon.</div>
      )}
      <div className="ws-grid">
        {sorted.map(function(w, i) { return <WsCard key={i} w={w} />; })}
      </div>
    </section>
  );
}

function Tools() {
  var toolColors = ["oklch(0.5 0.1 54)", "oklch(0.45 0.08 80)", "oklch(0.4 0.09 30)", "oklch(0.48 0.07 100)"];
  var toolGlyphs = ["◈", "◎", "⬡", "◇"];
  return (
    <section className="sec sec-tools" id="tools">
      <SecHeader num="05" label="TOOLS — FUNCTION STORE" />
      <div className="tools-intro">
        TouchDesigner components and templates. Used by artists at festivals and studios worldwide.
      </div>
      <div className="tools-grid">
        {window.TOOLS.map(function(t, i) {
          return (
            <article
              key={i}
              className="tool-card"
              data-cursor="VIEW PRODUCT"
              style={{ "--tool-c": toolColors[i % toolColors.length] }}
            >
              <div className="tool-img">
                <div className="tool-img-fx"></div>
                <div className="tool-glyph">{toolGlyphs[i % toolGlyphs.length]}</div>
                {t.tag && <span className="tool-tag">{t.tag}</span>}
              </div>
              <div className="tool-info">
                <span className="tool-title">{t.title}</span>
                <span className="tool-price">{t.price}</span>
                <p className="tool-desc">{t.desc}</p>
              </div>
            </article>
          );
        })}
      </div>
    </section>
  );
}

function Clients() {
  return (
    <section className="sec sec-clients">
      <SecHeader num="06" label="SELECTED CLIENTS" />
      <div className="clients-grid">
        {window.CLIENTS.map(function(c, i) {
          return (
            <div key={i} className="client-cell">
              <span className="client-idx">{String(i + 1).padStart(2, "0")}</span>
              <span className="client-name">{c}</span>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function ContactForm() {
  var [fields, setFields] = React.useState({ name: "", email: "", type: "", message: "" });
  var [status, setStatus] = React.useState("idle"); // idle | sending | success | error

  function set(k, v) { setFields(function(f) { return Object.assign({}, f, { [k]: v }); }); }

  function handleSubmit(e) {
    e.preventDefault();
    setStatus("sending");
    fetch("https://api.web3forms.com/submit", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        access_key: "2a69bb48-a239-491c-b1ff-162ef2d25b04",
        subject: "Portfolio enquiry" + (fields.type ? " — " + fields.type : ""),
        from_name: fields.name,
        name: fields.name,
        email: fields.email,
        type: fields.type,
        message: fields.message,
        botcheck: "",
      }),
    })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.success) {
          setStatus("success");
          setFields({ name: "", email: "", type: "", message: "" });
        } else {
          setStatus("error");
        }
      })
      .catch(function() { setStatus("error"); });
  }

  if (status === "success") {
    return (
      <div className="cf-success">
        <span className="cf-success-glyph">◉</span>
        <span>Message sent — I'll get back to you within 48 hours.</span>
      </div>
    );
  }

  return (
    <form className="cf" onSubmit={handleSubmit} noValidate>
      <div className="cf-row cf-row--2">
        <div className="cf-field">
          <label className="cf-label">Name</label>
          <input
            className="cf-input"
            type="text"
            required
            value={fields.name}
            onChange={function(e) { set("name", e.target.value); }}
            placeholder="Your name"
          />
        </div>
        <div className="cf-field">
          <label className="cf-label">Email</label>
          <input
            className="cf-input"
            type="email"
            required
            value={fields.email}
            onChange={function(e) { set("email", e.target.value); }}
            placeholder="your@email.com"
          />
        </div>
      </div>
      <div className="cf-field">
        <label className="cf-label">Type of enquiry</label>
        <div className="cf-select-wrap">
          <select
            className="cf-select"
            value={fields.type}
            onChange={function(e) { set("type", e.target.value); }}
          >
            <option value="">— select —</option>
            <option>Installation / commission</option>
            <option>Live performance system</option>
            <option>System design & consulting</option>
            <option>Workshop / education</option>
            <option>Collaboration</option>
            <option>Other</option>
          </select>
          <span className="cf-select-arrow">▾</span>
        </div>
      </div>
      <div className="cf-field">
        <label className="cf-label">Message</label>
        <textarea
          className="cf-textarea"
          required
          rows="5"
          value={fields.message}
          onChange={function(e) { set("message", e.target.value); }}
          placeholder="Tell me about the project…"
        />
      </div>
      {status === "error" && (
        <div className="cf-error">Something went wrong — try emailing directly.</div>
      )}
      <button className="cf-submit" type="submit" disabled={status === "sending"}>
        <span>{status === "sending" ? "Sending…" : "Send message"}</span>
        <span className="cf-submit-arrow">→</span>
      </button>
    </form>
  );
}

function Contact() {
  var [hover, setHover] = React.useState(false);
  return (
    <section className="sec sec-contact" id="contact">
      <SecHeader num="07" label="Contact" />
      <div className="contact-block">
        <div className="contact-eyebrow">
          <span className="contact-eyebrow-dot"></span>
          Available — Q3 2026
        </div>
        <h2 className="contact-h2">
          <span>Got a system that needs</span>
          <br />
          <span className="contact-h2-alt">building?</span>
        </h2>
        <div className="contact-cols">
          <div className="contact-col-info">
            <a
              href="mailto:dan@functionstore.xyz"
              className="contact-mail"
              onMouseEnter={function() { setHover(true); }}
              onMouseLeave={function() { setHover(false); }}
            >
              <span className={hover ? "contact-mail-glitch" : ""}>dan@functionstore.xyz</span>
              <span className="contact-mail-arrow">↗</span>
            </a>
            <div className="contact-grid">
              <div className="contact-item">
                <span className="contact-l">Social</span>
                <a className="contact-v" data-cursor="↗" href="https://instagram.com/function.str" target="_blank" rel="noopener">@function.str / instagram</a>
                <a className="contact-v" data-cursor="↗" href="https://youtube.com/@functionstore" target="_blank" rel="noopener">@functionstore / youtube</a>
                <a className="contact-v" data-cursor="↗" href="https://patreon.com/function_store" target="_blank" rel="noopener">/function_store / patreon</a>
              </div>
              <div className="contact-item">
                <span className="contact-l">Representation</span>
                <span className="contact-v">Self-represented — direct only</span>
              </div>
              <div className="contact-item">
                <span className="contact-l">Response time</span>
                <span className="contact-v">~ 48 hours, weekdays</span>
              </div>
            </div>
          </div>
          <div className="contact-col-form">
            <ContactForm />
          </div>
        </div>
      </div>
    </section>
  );
}

function SecHeader({ num, label }) {
  return (
    <div className="sec-head">
      <span className="sec-num">{num}</span>
      <span className="sec-rule"></span>
      <span className="sec-label">{label}</span>
      <span className="sec-rule sec-rule-ext"></span>
    </div>
  );
}

Object.assign(window, { About, Tutorials, Workshops, Tools, Clients, Contact, SecHeader });
