// Store page: Chambliss branded apparel (tees, hoodie, caps) and jobsite gear.
// Called "Merch" until the client renamed it; the route is /store and /merch
// still resolves here so old links and bookmarks keep working (components.jsx).
//
// Deliberately NOT a full store yet: "Add to cart" collects items in local
// state and the checkout button is a placeholder. When the client is ready to
// sell for real, point it at a store by setting window.CHAMBLISS_SHOP_URL (e.g.
// a Shopify storefront / cart-permalink) in index.html, same override pattern
// the FabTrk embeds use. handleCheckout() then opens it instead of showing the
// "coming soon" note; that's the only wiring change needed.
const CHECKOUT_URL =
  (typeof window !== 'undefined' && window.CHAMBLISS_SHOP_URL) || null;

// Where the print artwork comes from. Uses the real Chambliss logo; on dark
// garments it's knocked out to white via CSS filter (see .store-print-img--knock
// in styles.css), on light garments it stays the original steel-blue.
const STORE_LOGO = 'assets/img/logo.png';

// Garment palette. `knock: true` → print the logo in white (dark fabrics);
// `knock: false` → keep the original blue logo (light fabrics).
const STORE_COLORS = {
  Charcoal:        { hex: '#2c2c2e', knock: true },
  Black:           { hex: '#111113', knock: true },
  Steel:           { hex: '#868d95', knock: true },
  Navy:            { hex: '#1b2a3d', knock: true },
  Forest:          { hex: '#263d31', knock: true },
  'Safety Orange': { hex: '#e15d1c', knock: true },
  Sand:            { hex: '#d9cfba', knock: false },
  White:           { hex: '#f1f0ec', knock: false },
  // Gear, not apparel: the carbon weave reads near-black with a warm sheen.
  Carbon:          { hex: '#131315', knock: true },
};

const SHIRT_SIZES = ['S', 'M', 'L', 'XL', 'XXL'];

// Products carrying a `photo` show real product photography on a studio-white
// stage; the rest show the logo on the selected colourway.
const PRODUCTS = [
  { id: 'tee-pocket', shape: 'shirt', print: 'left',
    name: 'Pocket Tee', price: 28,
    blurb: 'Clean left-chest logo. The everyday, wear-it-anywhere option.',
    colors: ['Black', 'Navy', 'Sand'], sizes: SHIRT_SIZES },
  { id: 'tee-classic', shape: 'shirt', print: 'center',
    name: 'Steel Buildings Tee', price: 30,
    blurb: 'Heavyweight cotton with the full Chambliss mark across the chest. The classic.',
    colors: ['White', 'Steel', 'Forest'], sizes: SHIRT_SIZES },
  { id: 'hoodie', shape: 'hoodie', print: 'center',
    name: 'Jobsite Hoodie', price: 54,
    blurb: 'Midweight fleece pullover for cold mornings on site. Front pocket.',
    colors: ['Charcoal', 'Black', 'Forest'], sizes: SHIRT_SIZES },
  { id: 'cap-structured', shape: 'cap', print: 'center',
    name: 'Structured Cap', price: 26,
    blurb: 'Six-panel structured cap with an embroidered front logo.',
    colors: ['Black', 'Steel', 'Sand'], sizes: ['One size'] },
  { id: 'cap-trucker', shape: 'cap', print: 'center',
    name: 'Trucker Cap', price: 26,
    blurb: 'Foam-front trucker, mesh back, snapback fit. Summer standard.',
    colors: ['Black', 'Safety Orange', 'White'], sizes: ['One size'] },
  { id: 'hardhat-carbon', shape: 'hardhat', print: 'plate',
    name: 'Carbon Fiber Full-Brim Hard Hat', price: 115,
    blurb: 'Glossy carbon-weave shell with a full 360° brim and a brushed steel ' +
           'US flag plate. Ratchet suspension, and light enough to forget you have it on.',
    // TODO(client): confirm the ANSI class + price against the actual SKU before
    // this goes live. Carbon shells are conductive, so they are Class C, never
    // Class E. Do not promote it as electrical-rated.
    spec: 'ANSI Z89.1 · TYPE I · CLASS C',
    colors: ['Carbon'], sizes: ['One size'],
    photo: 'assets/img/store/hardhat-carbon-full-brim.jpg' },
];

// ── Product visual ─────────────────────────────────────────────────────
// Apparel shows the Chambliss logo on the selected colourway (knocked white on
// dark fabrics, kept steel-blue on light ones) rather than a drawn garment.
// Gear with real product photography shows the photo instead.
const StoreMockup = ({ product, colorName }) => {
  const c = STORE_COLORS[colorName] || STORE_COLORS.Charcoal;
  const showPhoto = !!product.photo;

  // Apparel sits on its own colourway. Photography gets a white stage, because
  // the shots are on a white studio backdrop and would otherwise show their own
  // rectangle floating on the card.
  const stage = showPhoto ? '#ffffff' : c.hex;
  // Adapt the corner label to the stage so it stays legible.
  const label = (!showPhoto && c.knock) ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.5)';

  return (
    <div className="store-stage" style={{ background: stage }}>
      {showPhoto ? (
        <img
          src={product.photo}
          alt={`${product.name}, ${colorName}`}
          className="store-photo-art"
          draggable="false"
        />
      ) : (
        <img
          src={STORE_LOGO}
          alt={`Chambliss logo on ${product.name}, ${colorName}`}
          className={`store-logo-art ${c.knock ? 'store-print-img--knock' : ''}`}
          draggable="false"
        />
      )}

      <span className="mono" style={{ position: 'absolute', bottom: 12, right: 12, zIndex: 2, fontSize: 10, letterSpacing: '0.06em', color: label }}>
        {colorName.toUpperCase()}
      </span>
    </div>
  );
};

// ── Product card ───────────────────────────────────────────────────────
const money = (n) => '$' + n;

const ProductCard = ({ product, onAdd }) => {
  const [colorName, setColorName] = React.useState(product.colors[0]);
  const oneSize = product.sizes.length === 1;
  const [size, setSize] = React.useState(oneSize ? product.sizes[0] : null);
  const [needSize, setNeedSize] = React.useState(false);
  const [added, setAdded] = React.useState(false);

  const add = () => {
    if (!oneSize && !size) { setNeedSize(true); return; }
    setNeedSize(false);
    onAdd({
      id: product.id, name: product.name, price: product.price,
      color: colorName, size: size || 'One size',
    });
    setAdded(true);
    if (typeof window !== 'undefined') window.setTimeout(() => setAdded(false), 1400);
  };

  return (
    <article className="spec-card lift" style={{ display: 'flex', flexDirection: 'column', gap: 0, padding: 0 }}>
      <StoreMockup product={product} colorName={colorName} />

      <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14, borderTop: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
          <h3 style={{ fontSize: 20 }}>{product.name}</h3>
          <span className="mono" style={{ fontSize: 15, color: 'var(--accent)', flexShrink: 0 }}>{money(product.price)}</span>
        </div>
        <p style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--fg-dim)', minHeight: 38 }}>{product.blurb}</p>

        {/* Safety rating / spec line, gear only */}
        {product.spec && (
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-faint)', letterSpacing: '0.08em' }}>
            {product.spec}
          </span>
        )}

        {/* Colour swatches */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-faint)', letterSpacing: '0.08em' }}>
            COLOR · <span style={{ color: 'var(--fg-dim)' }}>{colorName}</span>
          </span>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {product.colors.map((cn) => (
              <button
                key={cn}
                type="button"
                onClick={() => setColorName(cn)}
                className={`store-swatch ${cn === colorName ? 'active' : ''}`}
                style={{ background: STORE_COLORS[cn].hex }}
                aria-label={cn}
                title={cn}
              />
            ))}
          </div>
        </div>

        {/* Sizes */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <span className="mono" style={{ fontSize: 10, color: needSize ? 'var(--warn)' : 'var(--fg-faint)', letterSpacing: '0.08em' }}>
            {oneSize ? 'FIT' : (needSize ? 'PICK A SIZE' : 'SIZE')}
          </span>
          {oneSize ? (
            <span style={{ fontSize: 13, color: 'var(--fg-dim)' }}>One size · adjustable</span>
          ) : (
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {product.sizes.map((s) => (
                <button
                  key={s}
                  type="button"
                  onClick={() => { setSize(s); setNeedSize(false); }}
                  className={`store-size ${s === size ? 'active' : ''}`}
                >
                  {s}
                </button>
              ))}
            </div>
          )}
        </div>

        <button
          type="button"
          onClick={add}
          className={`btn ${added ? '' : 'btn-primary'}`}
          style={{ justifyContent: 'center', marginTop: 2 }}
        >
          {added ? (
            <>
              Added
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2.5 6.5 L5 9 L9.5 3.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </>
          ) : (
            <>
              Add to cart
              <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>
      </div>
    </article>
  );
};

// ── Cart (local only, no live checkout yet) ───────────────────────────
const StoreCart = ({ items, open, setOpen, remove, subtotal }) => {
  const [notice, setNotice] = React.useState(false);
  const count = items.reduce((n, i) => n + i.qty, 0);

  const checkout = () => {
    if (CHECKOUT_URL) { window.open(CHECKOUT_URL, '_blank', 'noopener'); return; }
    setNotice(true);
  };

  return (
    <>
      {/* Floating toggle */}
      <button
        type="button"
        className="store-cart-fab"
        onClick={() => setOpen(true)}
        aria-label={`Open cart (${count} item${count === 1 ? '' : 's'})`}
      >
        <svg width="18" height="18" viewBox="0 0 20 20" fill="none">
          <path d="M2 3 H5 L6.2 12 H16 L18 6 H6.6" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round"/>
          <circle cx="7.5" cy="16.5" r="1.4" fill="currentColor"/>
          <circle cx="15" cy="16.5" r="1.4" fill="currentColor"/>
        </svg>
        <span>Cart</span>
        {count > 0 && <span className="store-cart-count">{count}</span>}
      </button>

      {open && <div className="store-cart-backdrop" onClick={() => setOpen(false)} />}

      <aside className={`store-cart-drawer ${open ? 'open' : ''}`} aria-hidden={!open}>
        <div className="store-cart-head">
          <div>
            <div className="section-eyebrow" style={{ margin: 0 }}>
              <span>CART</span><span>/</span><span>{count} item{count === 1 ? '' : 's'}</span>
            </div>
          </div>
          <button type="button" className="btn btn-ghost" onClick={() => setOpen(false)} aria-label="Close cart" style={{ padding: 8 }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
        </div>

        <div className="store-cart-body">
          {items.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '48px 16px', color: 'var(--fg-faint)' }}>
              <svg width="34" height="34" viewBox="0 0 20 20" fill="none" style={{ margin: '0 auto 14px', opacity: 0.5 }}>
                <path d="M2 3 H5 L6.2 12 H16 L18 6 H6.6" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"/>
                <circle cx="7.5" cy="16.5" r="1.2" fill="currentColor"/>
                <circle cx="15" cy="16.5" r="1.2" fill="currentColor"/>
              </svg>
              <p style={{ fontSize: 13 }}>Your cart is empty.</p>
            </div>
          ) : (
            items.map((it) => (
              <div key={it.key} className="store-cart-line">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  <span style={{ fontSize: 14, fontWeight: 500 }}>{it.name}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-faint)' }}>
                    {it.color} · {it.size} · ×{it.qty}
                  </span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span className="mono" style={{ fontSize: 13 }}>{money(it.price * it.qty)}</span>
                  <button type="button" onClick={() => remove(it.key)} className="store-cart-remove" aria-label={`Remove ${it.name}`}>
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2.5 2.5 L9.5 9.5 M9.5 2.5 L2.5 9.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
                  </button>
                </div>
              </div>
            ))
          )}
        </div>

        <div className="store-cart-foot">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--fg-faint)', letterSpacing: '0.08em' }}>SUBTOTAL</span>
            <span style={{ fontSize: 22, fontWeight: 600 }}>{money(subtotal)}</span>
          </div>
          <button
            type="button"
            className="btn btn-primary btn-lg"
            style={{ width: '100%', justifyContent: 'center' }}
            onClick={checkout}
            disabled={items.length === 0}
          >
            {CHECKOUT_URL ? 'Checkout' : 'Checkout (coming soon)'}
            <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>
          {notice && !CHECKOUT_URL && (
            <p style={{ marginTop: 12, fontSize: 12, color: 'var(--fg-dim)', lineHeight: 1.5 }}>
              Online checkout isn’t live yet. To order, call{' '}
              <a href="tel:+13866881121" style={{ color: 'var(--accent)' }}>386.688.1121</a>{' '}
              or email us. Full checkout is coming soon.
            </p>
          )}
        </div>
      </aside>
    </>
  );
};

// ── Page ───────────────────────────────────────────────────────────────
const StoreHero = () => (
  <section style={{ position: 'relative', borderBottom: '1px solid var(--border)' }}>
    <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: 64 }}>
      <SectionEyebrow id="store" label="Store" />
      <h1 style={{ maxWidth: 820 }}>
        Chambliss Steel Buildings<br />
        <span style={{ color: 'var(--accent)' }}>store.</span>
      </h1>
    </div>
  </section>
);

const Store = ({ setRoute }) => {
  const [items, setItems] = React.useState([]);
  const [open, setOpen] = React.useState(false);

  const add = (item) => {
    const key = `${item.id}|${item.color}|${item.size}`;
    setItems((prev) => {
      const found = prev.find((l) => l.key === key);
      if (found) return prev.map((l) => (l.key === key ? { ...l, qty: l.qty + 1 } : l));
      return [...prev, { ...item, key, qty: 1 }];
    });
    setOpen(true); // surface the cart so the add is visible
  };
  const remove = (key) => setItems((prev) => prev.filter((l) => l.key !== key));
  const subtotal = items.reduce((n, i) => n + i.price * i.qty, 0);

  return (
    <div className="page-anim">
      <StoreHero />

      <section className="section">
        <div className="page">
          <div style={{ marginBottom: 40 }}>
            <SectionEyebrow label="The lineup" />
          </div>

          <div className="mob-stack store-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
            {PRODUCTS.map((p) => (
              <ProductCard key={p.id} product={p} onAdd={add} />
            ))}
          </div>
        </div>
      </section>

      {/* Cross-sell back to the core business */}
      <section className="section" style={{ borderBottom: 'none' }}>
        <div className="page">
          <div className="mob-stack" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 48, alignItems: 'end' }}>
            <h2 style={{ maxWidth: 640 }}>
              Here for a building, not a t-shirt?<br />
              <span style={{ color: 'var(--fg-faint)' }}>Let’s talk steel.</span>
            </h2>
            <button className="btn btn-primary btn-lg" onClick={() => setRoute('quote')} style={{ justifyContent: 'space-between' }}>
              Get a quote
              <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>
          </div>
        </div>
      </section>

      <StoreCart items={items} open={open} setOpen={setOpen} remove={remove} subtotal={subtotal} />
    </div>
  );
};

Object.assign(window, { Store });
