/* GECKO — Posts de Instagram (componentes) */
const { useRef: useRefP, useState: useStateP } = React;

const POST_IMG_KEY = "gecko_post_imgs_v1";
const loadPostImgs = () => { try { return JSON.parse(localStorage.getItem(POST_IMG_KEY) || "{}"); } catch (e) { return {}; } };
function resizePostImage(file, max = 900) {
  return new Promise((res, rej) => {
    if (!file || !file.type || !file.type.startsWith("image/")) return rej();
    const r = new FileReader();
    r.onload = () => {
      const im = new Image();
      im.onload = () => {
        let w = im.width, h = im.height;
        const s = Math.min(1, max / Math.max(w, h));
        w = Math.round(w * s); h = Math.round(h * s);
        const c = document.createElement("canvas"); c.width = w; c.height = h;
        const x = c.getContext("2d"); x.fillStyle = "#fff"; x.fillRect(0, 0, w, h); x.drawImage(im, 0, 0, w, h);
        res(c.toDataURL("image/jpeg", 0.85));
      };
      im.onerror = rej; im.src = r.result;
    };
    r.onerror = rej; r.readAsDataURL(file);
  });
}
function PostPhoto({ slot, radius = 20, label = "Foto del producto", children }) {
  const inputRef = useRefP();
  const [src, setSrc] = useStateP(() => loadPostImgs()[slot] || "");
  const [drag, setDrag] = useStateP(false);
  const set = (url) => {
    setSrc(url);
    const m = loadPostImgs();
    if (url) m[slot] = url; else delete m[slot];
    try { localStorage.setItem(POST_IMG_KEY, JSON.stringify(m)); } catch (e) {}
  };
  const handle = (f) => resizePostImage(f).then(set).catch(()=>{});
  return (
    <div className={"ph-img"+(src?" filled":"")} data-label={label}
      style={{flex:1, borderRadius:radius, position:"relative", overflow:"hidden", cursor:"pointer"}}
      onClick={()=>{ if(!src) inputRef.current.click(); }}
      onDragOver={e=>{ e.preventDefault(); setDrag(true); }}
      onDragLeave={()=>setDrag(false)}
      onDrop={e=>{ e.preventDefault(); setDrag(false); handle(e.dataTransfer.files[0]); }}>
      {src && <img src={src} alt="" style={{position:"absolute", inset:0, width:"100%", height:"100%", objectFit:"cover"}} />}
      {children}
      {src && <button onClick={e=>{ e.stopPropagation(); set(""); }} style={{position:"absolute", top:24, right:24, zIndex:3, width:48, height:48, borderRadius:10, border:"none", background:"rgba(20,21,26,.78)", color:"#fff", fontFamily:"var(--font-mono)", fontSize:24, cursor:"pointer"}}>✕</button>}
      {drag && <div style={{position:"absolute", inset:0, outline:"4px dashed var(--red)", outlineOffset:-12, background:"rgba(228,0,43,.08)", borderRadius:radius}}></div>}
      <input ref={inputRef} type="file" accept="image/*" style={{display:"none"}} onChange={e=>{ handle(e.target.files[0]); e.target.value=""; }} />
    </div>
  );
}

function WM({ light }) {
  return <span className={"wm"+(light?" light":"")}>GECKO<i className="m"></i></span>;
}
function Bar({ light }) {
  return (
    <div className="pbar">
      <WM light={light} />
      <span className={"handle"+(light?" light":"")}>@gecko.repuestos</span>
    </div>
  );
}
function Foot({ light, left, right }) {
  return (
    <div className={"pfoot"+(light?" light":"")}>
      <span>{left}</span>
      <span>{right}</span>
    </div>
  );
}

/* 1 — Lanzamiento */
function Post1() {
  return (
    <div className="post ink">
      <Bar light />
      <div className="pbody">
        <span className="kicker light">Nuevo · Panamá</span>
        <h1 className="huge" style={{fontSize:142, margin:"30px 0 0"}}>
          LA PRIMERA<br/>E&#8209;COMMERCE<br/>DE REPUESTOS<br/><span style={{color:"var(--red-bright)"}}>EN PANAMÁ.</span>
        </h1>
      </div>
      <Foot light left="Repuestos para autos" right="Despacho 24h" />
      <div className="tape haz" style={{bottom:0}}></div>
    </div>
  );
}

/* 2 — Promo 30% OFF */
function Post2() {
  return (
    <div className="post red">
      <Bar light />
      <div className="pbody">
        <span className="kicker light">Ofertas de apertura</span>
        <div className="huge" style={{fontSize:104, marginTop:24}}>HASTA</div>
        <div style={{display:"flex", alignItems:"flex-start", gap:22, marginTop:-4}}>
          <span className="huge" style={{fontSize:330, lineHeight:.8}}>30</span>
          <div style={{display:"flex", flexDirection:"column", paddingTop:30}}>
            <span className="huge" style={{fontSize:124, lineHeight:.88}}>%</span>
            <span className="huge" style={{fontSize:124, lineHeight:.88}}>OFF</span>
          </div>
        </div>
        <div style={{fontSize:42, fontWeight:600, marginTop:26, maxWidth:"20ch"}}>En frenos, baterías, suspensión y motor.</div>
      </div>
      <Foot light left="Cotiza por WhatsApp" right="Stock limitado" />
    </div>
  );
}

/* 3 — Despacho 24h */
function Post3() {
  return (
    <div className="post">
      <Bar />
      <div className="pbody">
        <span className="kicker">Logística</span>
        <h1 className="huge" style={{fontSize:128, margin:"28px 0 0"}}>DESPACHO EN</h1>
        <div style={{display:"flex", alignItems:"flex-end", gap:28, marginTop:6}}>
          <span className="huge" style={{fontSize:330, lineHeight:.8, color:"var(--red)"}}>&lt;24</span>
          <div style={{paddingBottom:42}}>
            <div className="huge" style={{fontSize:100, lineHeight:.85}}>HORAS</div>
            <p style={{fontSize:34, color:"var(--steel-2)", margin:"14px 0 0", maxWidth:"14ch", fontWeight:500}}>A todo Panamá, en menos de un día.</p>
          </div>
        </div>
      </div>
      <Foot left="@gecko.repuestos" right="Cobertura nacional" />
      <div className="tape haz" style={{bottom:0}}></div>
    </div>
  );
}

/* 4 — Todas las marcas */
function Post4() {
  const rows = ["EUROPEAS","CHINAS","AMERICANAS","COREANAS"];
  return (
    <div className="post ink">
      <Bar light />
      <div className="pbody">
        <span className="kicker light">Cobertura total</span>
        <h1 className="huge" style={{fontSize:118, margin:"26px 0 36px"}}>TODAS LAS<br/>MARCAS.</h1>
        <div style={{display:"flex", flexDirection:"column", gap:0}}>
          {rows.map((r,i) => (
            <div key={r} style={{display:"flex", alignItems:"baseline", justifyContent:"space-between", padding:"20px 0", borderTop:"2px solid rgba(255,255,255,.16)"}}>
              <span className="huge" style={{fontSize:62, color: i%2 ? "#fff":"var(--red-bright)"}}>{r}</span>
              <span className="mono" style={{fontSize:22, letterSpacing:".1em", color:"rgba(255,255,255,.45)"}}>{`0${i+1}`}</span>
            </div>
          ))}
        </div>
        <p className="mono" style={{fontSize:24, letterSpacing:".06em", color:"rgba(255,255,255,.55)", marginTop:30}}>Toyota · Hyundai · Kia · VW · BMW · Chery · BYD · y más</p>
      </div>
      <Foot light left="Repuestos para autos" right="Panamá" />
    </div>
  );
}

/* 5 — Producto destacado */
function Post5() {
  return (
    <div className="post">
      <Bar />
      <div style={{flex:1, display:"flex", flexDirection:"column", padding:"0 60px 10px"}}>
        <PostPhoto slot="post5" radius={20} label="Foto del producto">
          <span style={{position:"absolute", top:26, left:26, zIndex:2}} className="pill">−29% OFF</span>
        </PostPhoto>
        <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-end", paddingTop:34}}>
          <div>
            <div className="mono" style={{fontSize:24, letterSpacing:".1em", textTransform:"uppercase", color:"var(--red)"}}>Frenos · Coreanas</div>
            <h2 className="huge" style={{fontSize:78, margin:"10px 0 6px"}}>Pastillas<br/>de freno</h2>
            <div className="mono" style={{fontSize:24, color:"var(--steel-2)"}}>SKU GK&#8209;FR&#8209;4820</div>
          </div>
          <div style={{textAlign:"right"}}>
            <div className="mono" style={{fontSize:30, color:"var(--steel)", textDecoration:"line-through"}}>B/. 54.90</div>
            <div className="huge" style={{fontSize:110, color:"var(--red)", lineHeight:.9}}>B/.38<span style={{fontSize:60}}>.90</span></div>
          </div>
        </div>
      </div>
      <Foot left="Cotiza por WhatsApp" right="Despacho 24h" />
    </div>
  );
}

/* 6 — Talleres / mayoreo */
function Post6() {
  const items = ["Descuentos por volumen","Línea directa por WhatsApp","Despacho prioritario 24h"];
  return (
    <div className="post red">
      <Bar light />
      <div className="pbody">
        <span className="kicker light">Talleres &amp; revendedores</span>
        <h1 className="huge" style={{fontSize:118, margin:"26px 0 44px"}}>PRECIOS DE<br/>MAYOREO PARA<br/>TU NEGOCIO.</h1>
        <div style={{display:"flex", flexDirection:"column", gap:24}}>
          {items.map(it => (
            <div key={it} style={{display:"flex", alignItems:"center", gap:24, fontSize:42, fontWeight:600}}>
              <span style={{width:18, height:18, background:"#fff", flex:"none", transform:"skewX(-16deg)"}}></span>{it}
            </div>
          ))}
        </div>
      </div>
      <Foot light left="Escríbenos hoy" right="@gecko.repuestos" />
    </div>
  );
}

/* 7 — Cómo pedir */
function Post7() {
  const steps = [["01","Busca tu pieza","Marca, modelo y categoría"],["02","Cotiza por WhatsApp","Confirmamos precio y stock"],["03","Recíbela en 24h","Despacho a todo Panamá"]];
  return (
    <div className="post">
      <Bar />
      <div className="pbody">
        <span className="kicker">Cómo pedir</span>
        <h1 className="huge" style={{fontSize:138, margin:"26px 0 48px"}}>PEDIR ES<br/>FÁCIL.</h1>
        <div style={{display:"flex", flexDirection:"column", gap:0}}>
          {steps.map(([n,h,d]) => (
            <div key={n} style={{display:"flex", alignItems:"center", gap:36, padding:"30px 0", borderTop:"2px solid var(--line)"}}>
              <span className="huge" style={{fontSize:84, color:"var(--red)", width:120, flex:"none"}}>{n}</span>
              <div>
                <div className="huge" style={{fontSize:54}}>{h}</div>
                <div style={{fontSize:32, color:"var(--steel-2)", marginTop:4}}>{d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <Foot left="@gecko.repuestos" right="Despacho 24h" />
    </div>
  );
}

Object.assign(window, { Post1, Post2, Post3, Post4, Post5, Post6, Post7 });
