/* global React, window */
const DS = window.ACONADesignSystem_e7dd84;
const { Button, Eyebrow, Tag, Stat, ArrowLink, ServiceCard, InsightCard, Testimonial, SiteHeader, SiteFooter, SectionHeader } = DS;

const IMG = '../../assets/photography/';
const LOGO = '../../assets/logos/';
const NAV = [
  { label: 'Services', href: '#services' },
  { label: 'Experience', href: '#/experience' },
  { label: 'Gallery', href: '#/gallery' },
  { label: 'About', href: '#/about' },
  { label: 'Insights', href: '#insights' },
];

/* -------- section-registration calibrator (hero x-ray reveal) -------- */
function AlignPanel() {
  const readNum = (k, d) => { const v = parseFloat(localStorage.getItem(k)); return isNaN(v) ? d : v; };
  const [open, setOpen] = React.useState(false);
  const [x, setX] = React.useState(() => readNum('acona_plan_x', 0));
  const [y, setY] = React.useState(() => readNum('acona_plan_y', 0));
  const [scale, setScale] = React.useState(() => readNum('acona_plan_scale', 1));
  const [copied, setCopied] = React.useState(false);

  React.useEffect(() => {
    const el = document.querySelector('.hero__img--plan');
    if (el) {
      el.style.setProperty('--plan-x', x + 'px');
      el.style.setProperty('--plan-y', y + 'px');
      el.style.setProperty('--plan-scale', String(scale));
    }
    localStorage.setItem('acona_plan_x', String(x));
    localStorage.setItem('acona_plan_y', String(y));
    localStorage.setItem('acona_plan_scale', String(scale));
  }, [x, y, scale]);

  const cssText = '--plan-x: ' + x + 'px; --plan-y: ' + y + 'px; --plan-scale: ' + scale + ';';
  const copy = () => { try { navigator.clipboard.writeText(cssText); setCopied(true); setTimeout(() => setCopied(false), 1200); } catch (e) {} };
  const reset = () => { setX(0); setY(0); setScale(1); };

  const panel = { position: 'fixed', right: '20px', bottom: '20px', zIndex: 95, fontFamily: 'var(--font-sans)' };
  const row = { display: 'grid', gridTemplateColumns: '52px 1fr 42px', alignItems: 'center', gap: '10px', margin: '9px 0' };
  const lab = { fontSize: '11px', letterSpacing: '.12em', textTransform: 'uppercase', color: 'rgba(255,255,255,.7)' };
  const val = { fontSize: '12px', fontVariantNumeric: 'tabular-nums', textAlign: 'right', color: '#fff' };
  const rng = { width: '100%', accentColor: 'var(--clay-400)' };

  if (!open) {
    return (
      <button onClick={() => setOpen(true)} style={{ ...panel, cursor: 'pointer', background: 'rgba(10,18,26,.9)', color: '#fff', border: '1px solid rgba(255,255,255,.18)', padding: '9px 14px', fontSize: '12px', letterSpacing: '.08em', textTransform: 'uppercase', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '8px' }}>
        <span style={{ color: 'var(--clay-400)' }}>◧</span> Align section
      </button>
    );
  }

  return (
    <div style={panel}>
      <div style={{ width: '272px', background: 'rgba(10,18,26,.92)', backdropFilter: 'blur(8px)', border: '1px solid rgba(255,255,255,.16)', color: '#fff', padding: '14px 16px 16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
          <span style={{ fontSize: '12px', letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: 700 }}>Section registration</span>
          <button onClick={() => setOpen(false)} style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,.7)', cursor: 'pointer', fontSize: '18px', lineHeight: 1, padding: 0 }} aria-label="Collapse">×</button>
        </div>
        <div style={{ fontSize: '11px', color: 'rgba(255,255,255,.5)', marginBottom: '6px' }}>Nudge the section render to register with the photo.</div>
        <div style={row}>
          <span style={lab}>Horiz.</span>
          <input type="range" min={-500} max={500} step={1} value={x} onChange={(e) => setX(Number(e.target.value))} style={rng} />
          <span style={val}>{x}</span>
        </div>
        <div style={row}>
          <span style={lab}>Vert.</span>
          <input type="range" min={-400} max={400} step={1} value={y} onChange={(e) => setY(Number(e.target.value))} style={rng} />
          <span style={val}>{y}</span>
        </div>
        <div style={row}>
          <span style={lab}>Scale</span>
          <input type="range" min={0.5} max={2} step={0.01} value={scale} onChange={(e) => setScale(Number(e.target.value))} style={rng} />
          <span style={val}>{scale.toFixed(2)}</span>
        </div>
        <div style={{ marginTop: '12px', fontFamily: 'ui-monospace, Menlo, monospace', fontSize: '10.5px', color: 'rgba(255,255,255,.75)', background: 'rgba(255,255,255,.06)', padding: '8px 10px', wordBreak: 'break-all' }}>{cssText}</div>
        <div style={{ display: 'flex', gap: '8px', marginTop: '10px' }}>
          <button onClick={copy} style={{ flex: 1, cursor: 'pointer', background: 'var(--clay-400)', color: '#fff', border: 'none', padding: '8px 0', fontSize: '11px', letterSpacing: '.08em', textTransform: 'uppercase', fontWeight: 600 }}>{copied ? 'Copied' : 'Copy CSS'}</button>
          <button onClick={reset} style={{ cursor: 'pointer', background: 'transparent', color: 'rgba(255,255,255,.8)', border: '1px solid rgba(255,255,255,.24)', padding: '8px 12px', fontSize: '11px', letterSpacing: '.08em', textTransform: 'uppercase', fontWeight: 600 }}>Reset</button>
        </div>
      </div>
    </div>
  );
}

/* ---------------- HERO ---------------- */
function Hero() {
  const heroRef = React.useRef(null);
  const draggingRef = React.useRef(false);
  const [rx, setRx] = React.useState(50);

  const setFromX = React.useCallback((clientX) => {
    const el = heroRef.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const p = ((clientX - r.left) / r.width) * 100;
    setRx(Math.max(6, Math.min(94, p)));
  }, []);

  React.useEffect(() => {
    const move = (e) => { if (draggingRef.current) setFromX(e.clientX); };
    const up = () => { if (draggingRef.current) { draggingRef.current = false; document.body.style.userSelect = ''; } };
    window.addEventListener('pointermove', move);
    window.addEventListener('pointerup', up);
    return () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
  }, [setFromX]);

  const onDown = (e) => { e.preventDefault(); draggingRef.current = true; document.body.style.userSelect = 'none'; e.currentTarget.focus(); setFromX(e.clientX); };
  const onKey = (e) => {
    if (e.key === 'ArrowLeft') { e.preventDefault(); setRx((v) => Math.max(6, v - 2)); }
    else if (e.key === 'ArrowRight') { e.preventDefault(); setRx((v) => Math.min(94, v + 2)); }
  };

  return (
    <section className="hero" id="top" ref={heroRef}>
      <img className="hero__img hero__img--plan" src={'../../assets/photography/madison-vision.png'} alt="Madison Square Boys & Girls Club — architectural section showing the interior program" />
      <img className="hero__img hero__img--real" src={'../../assets/photography/madison-boys-girls-club.jpg'} alt="Madison Square Boys & Girls Club, Harlem — the built clubhouse at dusk" style={{ clipPath: 'inset(0 0 0 ' + rx + '%)' }} />
      <div className="hero__scrim" />
      <div className="hero__grid" />
      <div className="hero__ticks" style={{ top: '96px', left: 'var(--gutter)', borderTop: '2px solid', borderLeft: '2px solid' }} />
      <div className="hero__ticks" style={{ bottom: '30px', right: 'var(--gutter)', borderBottom: '2px solid', borderRight: '2px solid' }} />
      <div className="hero__reveal-handle" style={{ left: rx + '%' }}>
        <div className="hero__reveal-grab" role="slider" tabIndex={0}
             aria-label="Drag to reveal the section drawing or the built photograph"
             aria-valuemin={6} aria-valuemax={94} aria-valuenow={Math.round(rx)}
             onPointerDown={onDown} onKeyDown={onKey}>
          <div className="hero__reveal-knob">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <polyline points="9 7 4 12 9 17" /><polyline points="15 7 20 12 15 17" />
            </svg>
          </div>
        </div>
      </div>
      <span className="hero__meta">Madison Sq. Boys &amp; Girls Club · Harlem</span>
      <div className="container container--wide hero__inner">
        <div className="hero__eyebrow ac-fade ac-d1">Community · Impact · Place</div>
        <h1 className="hero__title ac-fade ac-d2">We turn mission into place.</h1>
        <p className="hero__sub ac-fade ac-d3">ACONA is a Brooklyn-based real estate and owner's representation firm guiding mission-driven organizations from the first planning conversation through occupancy.</p>
        <div className="hero__actions ac-fade ac-d4">
          <Button variant="primary" onDark arrow href="#/contact">Start a project</Button>
          <Button variant="secondary" onDark href="#/experience">Explore our work</Button>
        </div>
      </div>
      <AlignPanel />
    </section>
  );
}

/* ---------------- POSITIONING ---------------- */
function Intro() {
  return (
    <section className="section section--paper" id="intro">
      <div className="container container--wide">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '56px', alignItems: 'start' }}>
          <div>
            <Eyebrow number="01" rule>Who we are</Eyebrow>
            <p style={{ fontFamily: 'var(--font-serif)', fontSize: 'var(--text-3xl)', lineHeight: 1.2, letterSpacing: '-0.01em', color: 'var(--text-strong)', margin: '26px 0 0', textWrap: 'balance' }}>
              We help mission-driven organizations translate purpose into <em style={{ color: 'var(--navy-600)' }}>place</em> — under the real-world constraints of capital, funding, approvals and construction.
            </p>
          </div>
          <div style={{ paddingTop: '10px' }}>
            <p style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--text-md)', lineHeight: 1.7, color: 'var(--text-body)', margin: '0 0 20px' }}>
              Lifelong friends from the same Brooklyn block, Matt Hopkins and Toby Rappaport founded ACONA in 2021 to give New York's cultural and civic institutions senior-led advisory on every assignment.
            </p>
            <p style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--text-md)', lineHeight: 1.7, color: 'var(--text-muted)', margin: '0 0 28px' }}>
              Small by design, we scale a trusted cohort of consultants up or down to fit each project — never sacrificing budget, vision or direct principal attention.
            </p>
            <ArrowLink href="#/about" size="lg">Meet Matt &amp; Toby</ArrowLink>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- METRICS ---------------- */
function Metrics() {
  return (
    <section className="section section--tight section--ink">
      <div className="container container--wide">
        <div className="metrics metrics--ruled">
          <div><Stat value="$100M+" label="Under management" onDark /></div>
          <div><Stat value="$60M+" label="Public funding secured" onDark /></div>
          <div><Stat value="20+" label="Years combined experience" onDark /></div>
          <div><Stat value="60+" label="Organizations served" onDark tone="accent" /></div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- SERVICES ---------------- */
function Services() {
  return (
    <section className="section section--warm" id="services">
      <div className="container container--wide">
        <SectionHeader
          layout="between"
          eyebrow="What we do"
          eyebrowNumber="02"
          title="Three disciplines, one senior team."
          intro="ACONA is a one-stop advisor across the full project lifecycle — brokerage, owner's representation and the public funding that makes ambitious projects possible."
          action={<Button variant="secondary" href="#services">All services</Button>}
        />
        <div className="grid-3" style={{ marginTop: 'var(--space-7)', gap: '24px' }}>
          <ServiceCard number="01" title="Real Estate Brokerage"
            description="Tenant and landlord representation with creative leasing strategies and space search across New York."
            items={['Site & space search', 'Comparative cost analysis', 'Lease & purchase negotiation']} />
          <ServiceCard number="02" title="Owner's Representation"
            description="Independent project leadership from planning and design through construction and closeout."
            items={['Feasibility & master planning', 'Budget, schedule & team selection', 'Construction oversight & closeout']} />
          <ServiceCard number="03" title="Public Funding Support"
            description="NYSCA, DCLA and city-agency strategy that turns capital allocations into finished space."
            items={['Funding application strategy', 'City-agency coordination', 'Capital allocation management']} />
        </div>
      </div>
    </section>
  );
}

/* ---------------- BAM BAND (complementary full-bleed) ---------------- */
function AdaptiveBand() {
  return (
    <section className="band">
      <img className="band__img" src={'../../assets/photography/bam-fisher.jpg'} alt="BAM Richard B. Fisher Building, Brooklyn" />
      <div className="band__scrim" />
      <div className="container container--wide band__inner">
        <div style={{ maxWidth: '620px' }}>
          <Eyebrow tone="on-dark" rule>Adaptive reuse &amp; complex delivery</Eyebrow>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: '#fff', fontSize: 'var(--text-3xl)', lineHeight: 1.02, letterSpacing: '-0.02em', margin: '26px 0 22px', textWrap: 'balance' }}>
            Helping institutions modernize without losing their identity.
          </h2>
          <p style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--text-md)', lineHeight: 1.65, color: 'var(--navy-100)', margin: '0 0 32px', maxWidth: '52ch' }}>
            From BAM's Fisher Building to the Manny Cantor Center, our principals have delivered historically sensitive, community-defining capital projects across New York — steering acoustics, accessibility, landmarks approvals and layered public funding.
          </p>
          <ArrowLink href="#/experience" onDark size="lg">See our experience</ArrowLink>
        </div>
      </div>
    </section>
  );
}

/* ---------------- FEATURED CASE STUDY (wide section image) ---------------- */
function CaseStudy() {
  return (
    <section className="section section--paper" id="casestudy">
      <div className="container container--wide">
        <SectionHeader
          eyebrow="Principal-led experience"
          eyebrowNumber="03"
          title="Madison Square Boys & Girls Club"
          intro="The Pinkerton Clubhouse — a new home for the youth who need it most."
        />
      </div>
      <div className="container container--wide" style={{ marginTop: 'var(--space-6)' }}>
        <img src={'../../assets/photography/madison-section.jpg'} alt="Architectural section — Pinkerton Clubhouse, Harlem"
          style={{ width: '100%', height: 'auto', borderRadius: 'var(--radius-md)', display: 'block' }} />
      </div>
      <div className="container container--wide" style={{ marginTop: 'var(--space-6)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '56px', alignItems: 'start' }}>
          <p style={{ fontFamily: 'var(--font-serif)', fontSize: 'var(--text-xl)', lineHeight: 1.4, color: 'var(--text-strong)', margin: 0 }}>
            A 45,000-square-foot ground-up clubhouse in Harlem — classrooms, art rooms, athletic facilities, a screening room and a recording studio — delivered through a complex approvals process spanning DOT, MTA, DEP, DOB and FDNY.
          </p>
          <div>
            <div style={{ display: 'flex', gap: '40px', marginBottom: '24px' }}>
              <Stat value="45,000" unit="sf" label="New clubhouse" size="sm" tone="accent" />
              <Stat value="Harlem" label="Ground-up construction" size="sm" />
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginBottom: '24px' }}>
              <Tag variant="soft">Owner's Representation</Tag>
              <Tag variant="soft" tone="clay">Public Funding</Tag>
              <Tag variant="soft" tone="neutral">City-Agency Coordination</Tag>
            </div>
            <ArrowLink href="#/project">Read the full case study</ArrowLink>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- CURRENT WORK (editorial list, no invented imagery) ---------------- */
const CURRENT = [
  { sector: 'Performing Arts', title: 'The Joyce Theater', href: '#',
    desc: 'Owner’s representation for the adaptive reuse of a 58,000 sf former Boys & Girls Club in the East Village into a performance and rehearsal home for dance — anchored by a $13M DCLA capital allocation.',
    tags: ['Owner’s Representation', 'Public Funding'] },
  { sector: 'Arts & Culture', title: 'Brooklyn Arts Exchange', href: '#',
    desc: 'A feasibility study and master plan for a beloved multigenerational arts organization — HVAC modernization and accessibility upgrades funded through NYSCA.',
    tags: ['Tenant Representation', 'Owner’s Rep', 'Public Funding'] },
  { sector: 'Performing Arts', title: 'Casa Belongó · Afro Latin Jazz Alliance', href: '#',
    desc: 'Owner’s representation for a 20,000 sf music venue and community space at the base of East Harlem’s Timbale Terrace — with Diller Scofidio + Renfro and Turner Construction.',
    tags: ['Owner’s Representation'] },
];

function CurrentWork() {
  return (
    <section className="section section--warm">
      <div className="container container--wide">
        <SectionHeader
          layout="between"
          eyebrow="Currently underway"
          title="Places we’re helping bring to life."
          action={<ArrowLink href="#/experience">View all experience</ArrowLink>}
        />
        <div style={{ marginTop: 'var(--space-6)', borderBottom: '1px solid var(--border-hairline)' }}>
          {CURRENT.map((p, i) => (
            <a key={i} href={p.href} className="work-row" style={{
              display: 'grid', gridTemplateColumns: '0.5fr 2fr 1.1fr auto', gap: '32px', alignItems: 'center',
              padding: '30px 0', borderTop: '1px solid var(--border-hairline)', textDecoration: 'none', color: 'inherit',
            }}>
              <span style={{ fontFamily: 'var(--font-eyebrow)', fontSize: 'var(--text-xs)', fontWeight: 600, letterSpacing: 'var(--tracking-eyebrow)', textTransform: 'uppercase', color: 'var(--text-accent)' }}>{p.sector}</span>
              <div>
                <h3 style={{ fontFamily: 'var(--font-heading)', fontWeight: 400, fontSize: 'var(--text-xl)', letterSpacing: 'var(--tracking-snug)', color: 'var(--text-strong)', margin: '0 0 8px' }}>{p.title}</h3>
                <p style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--text-sm)', lineHeight: 1.55, color: 'var(--text-muted)', margin: 0, maxWidth: '54ch' }}>{p.desc}</p>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '7px' }}>
                {p.tags.map((t, j) => <Tag key={j} size="sm">{t}</Tag>)}
              </div>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--navy-700)" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><line x1="4" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></svg>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- TESTIMONIAL ---------------- */
function Quote() {
  return (
    <section className="section section--paper">
      <div className="container" style={{ maxWidth: '960px' }}>
        <Testimonial size="lg"
          quote={<>&ldquo;Our work for BAX brought our brokerage, owner&rsquo;s representation and public-funding expertise together to partner with a <em>beloved</em> Brooklyn arts organization.&rdquo;</>}
          name="Toby Rappaport" role="Co-Founder, ACONA Real Estate Advisors" />
      </div>
    </section>
  );
}

/* ---------------- INSIGHTS ---------------- */
function Insights() {
  return (
    <section className="section section--warm" id="insights">
      <div className="container container--wide">
        <SectionHeader layout="between" eyebrow="Insights & Resources"
          title="What we’re reading, learning and seeing."
          action={<ArrowLink href="#insights">All insights</ArrowLink>} />
        <div className="insights" style={{ marginTop: 'var(--space-6)' }}>
          <InsightCard category="Capital Projects" date="Guide" title="How to select an architect for a mission-driven project"
            excerpt="A practical framework for choosing a design partner who understands your mission, your building and your funding realities." />
          <InsightCard category="Advisory" date="Explainer" title="Owner’s Representative vs. Construction Manager"
            excerpt="Who works for whom, and why an independent advocate changes the outcome of a capital project." />
          <InsightCard category="Public Funding" date="Guide" title="Understanding NYSCA & DCLA capital funding"
            excerpt="How New York’s cultural capital programs work — and how to position your organization to win an allocation." />
          <InsightCard category="Board Leadership" date="Checklist" title="Preparing your board for a major capital project"
            excerpt="The questions every board should answer before committing to build, renovate or relocate." />
        </div>
      </div>
    </section>
  );
}

/* ---------------- CTA ---------------- */
function CTA() {
  return (
    <section className="section section--ink" id="contact">
      <div className="container container--wide">
        <div className="cta-band">
          <div style={{ maxWidth: '640px' }}>
            <Eyebrow tone="on-dark" rule>Let&rsquo;s begin</Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: '#fff', fontSize: 'var(--text-3xl)', lineHeight: 1.02, letterSpacing: '-0.02em', margin: '24px 0 20px', textWrap: 'balance' }}>
              Let&rsquo;s discuss your next project.
            </h2>
            <p style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--text-md)', lineHeight: 1.6, color: 'var(--navy-200)', margin: 0, maxWidth: '48ch' }}>
              Whether you&rsquo;re weighing a lease, planning a capital project or navigating public funding, we&rsquo;d love to hear what you&rsquo;re working on.
            </p>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
            <Button variant="primary" onDark arrow href="#/contact">Start a project</Button>
            <Button variant="ghost" onDark arrow href="mailto:hello@aconarea.com">hello@aconarea.com</Button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- PAGE ---------------- */
function Home() {
  return (
    <React.Fragment>
      <SiteHeader logo={'../../assets/logos/acona-logo.png'} logoWhite={'../../assets/logos/acona-logo-white.png'} links={NAV} active={null} cta={{ label: 'Start a project', href: '#/contact' }} />
      <Hero />
      <Intro />
      <Metrics />
      <Services />
      <AdaptiveBand />
      <CaseStudy />
      <CurrentWork />
      <Quote />
      <Insights />
      <CTA />
      <SiteFooter logoWhite={'../../assets/logos/acona-logo-white.png'} />
    </React.Fragment>
  );
}

window.ACONA = window.ACONA || {};
window.ACONA.Home = Home;
