// Portfolio, published FabTrk projects for this account, shown as live 3D models.
//
// Data comes from FabTrk's public "portfolio" endpoint, keyed by one capability
// token per account. In FabTrk, open a project's model and hit "Publish", every
// published project shows up under the account's portfolio token. Put that token
// in index.html as window.CHAMBLISS_PORTFOLIO_TOKEN and this page fills in. Until
// then it shows a friendly placeholder.
const FABTRK_API_URL =
  (typeof window !== 'undefined' && window.FABTRK_API_URL) || 'https://api.fabtrk.com';
const CHAMBLISS_PORTFOLIO_TOKEN =
  (typeof window !== 'undefined' && window.CHAMBLISS_PORTFOLIO_TOKEN) || null;
// The FabTrk app origin that serves /embed/project/<token>, reuse the designer
// URL's host so prod/dev stay in sync with the other embeds.
const FABTRK_APP_ORIGIN = (() => {
  try { return new URL(FABTRK_DESIGNER_URL).origin; } catch (e) { return 'https://fabtrk.com'; }
})();

const PortfolioHero = () => (
  <section style={{ borderBottom: '1px solid var(--border)', position: 'relative' }}>
    <div className="grid-bg" style={{
      position: 'absolute', inset: 0, opacity: 0.4,
      maskImage: 'linear-gradient(to bottom, black, transparent)',
      WebkitMaskImage: 'linear-gradient(to bottom, black, transparent)',
    }} />
    <div className="page" style={{ position: 'relative', paddingTop: 80, paddingBottom: 56 }}>
      <SectionEyebrow id="portfolio" label="Portfolio" />
      <h1 style={{ maxWidth: 900 }}>
        Explore our builds<br /><span style={{ color: 'var(--accent)' }}>in real 3D.</span>
      </h1>
    </div>
  </section>
);

const PortfolioCard = ({ project }) => (
  <div className="spec-card lift" style={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
    {project.hasModel ? (
      <ModelViewerFrame
        src={`${FABTRK_APP_ORIGIN}/embed/project/${project.token}`}
        tag={null}
        title={`${project.name}, 3D fabrication model`}
        cta="View the 3D model"
        sub={`${project.number} · LIVE FABRICATION MODEL`}
        height={380}
      />
    ) : (
      <div className="img-slot" style={{ height: 380 }}>
        <div className="label-wrap"><span>{project.name}</span></div>
      </div>
    )}
    <div style={{ padding: 20, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
      <h3 style={{ fontSize: 20 }}>{project.name}</h3>
      <span className="mono" style={{ fontSize: 11, color: 'var(--fg-faint)' }}>{project.number}</span>
    </div>
  </div>
);

const PortfolioEmpty = ({ setRoute }) => (
  <div style={{ border: '1px solid var(--border)', background: 'var(--bg-card)', padding: 56, textAlign: 'center' }}>
    <div style={{ display: 'inline-block' }}>
      <SectionEyebrow id="soon" label="Coming soon" />
    </div>
    <h2 style={{ maxWidth: 640, margin: '0 auto' }}>Published builds land here.</h2>
    <p style={{ margin: '16px auto 0', maxWidth: 560, color: 'var(--fg-dim)', fontSize: 16, lineHeight: 1.55 }}>
      We're adding interactive 3D models of completed projects. In the meantime,
      design your own building or reach out for a quote.
    </p>
    <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
      <button className="btn btn-primary" onClick={() => setRoute('configurator')}>
        Design in 3D
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M3 6 L9 6 M6 3 L9 6 L6 9" stroke="currentColor" strokeWidth="1.6"/></svg>
      </button>
      <button className="btn" onClick={() => setRoute('quote')}>Get a quote</button>
    </div>
  </div>
);

const Portfolio = ({ setRoute }) => {
  const [state, setState] = React.useState(() => ({ kind: CHAMBLISS_PORTFOLIO_TOKEN ? 'loading' : 'unset' }));

  React.useEffect(() => {
    if (!CHAMBLISS_PORTFOLIO_TOKEN) return;
    let active = true;
    fetch(`${FABTRK_API_URL}/api/v1/public/portfolio/${CHAMBLISS_PORTFOLIO_TOKEN}?t=${Date.now()}`, { cache: 'no-store' })
      .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
      .then((body) => { if (active) setState({ kind: 'ready', projects: (body.data && body.data.projects) || [] }); })
      .catch(() => { if (active) setState({ kind: 'error' }); });
    return () => { active = false; };
  }, []);

  const showEmpty =
    state.kind === 'unset' || state.kind === 'error' ||
    (state.kind === 'ready' && (!state.projects || state.projects.length === 0));

  return (
    <div className="page-anim">
      <PortfolioHero />
      <section className="section" style={{ borderBottom: 'none' }}>
        <div className="page">
          {state.kind === 'loading' && (
            <p className="mono" style={{ color: 'var(--fg-faint)', fontSize: 12, letterSpacing: '0.08em' }}>
              LOADING PUBLISHED PROJECTS…
            </p>
          )}
          {showEmpty && <PortfolioEmpty setRoute={setRoute} />}
          {state.kind === 'ready' && state.projects && state.projects.length > 0 && (
            <div className="mob-stack" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 20 }}>
              {state.projects.map((p) => <PortfolioCard key={p.token} project={p} />)}
            </div>
          )}
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { Portfolio });
