/* sema ikutoke Collections — Builder, Storefront, Checkout views */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB, useMemo: useMemoB } = React;

/* ─── Block definitions ─── */
const BLOCK_DEFS = {
  hero:       { name: "Hero",        glyph: "H", default: { title: "Field Notes — Vol. 03", subtitle: "A small book of photographs and essays from a year spent walking.", emph: "Vol. 03" } },
  collection: { name: "Collection",  glyph: "C", default: { heading: "What's inside", count: 6, label: "Photographs" } },
  buybar:     { name: "Buy bar",     glyph: "$", default: { title: "Buy the collection", price: "1,200", subtitle: "23 photographs · 14 essays · 42 MB · DRM-free" } },
  quote:      { name: "Pull-quote",  glyph: "❝", default: { text: "A small, quieter way to make a living from your work.", attribution: "— a kind reader" } },
  text:       { name: "Text",        glyph: "T", default: { body: "sema ikutoke is built around the idea that selling work shouldn't get in the way of making it. Write here." } },
  gallery:    { name: "Gallery",     glyph: "▣", default: { count: 4 } },
  divider:    { name: "Divider",     glyph: "—", default: {} },
};

const DEFAULT_PAGE = [
  { id: "b1", type: "hero",       data: { ...BLOCK_DEFS.hero.default } },
  { id: "b2", type: "collection", data: { ...BLOCK_DEFS.collection.default } },
  { id: "b3", type: "quote",      data: { ...BLOCK_DEFS.quote.default } },
  { id: "b4", type: "buybar",     data: { ...BLOCK_DEFS.buybar.default } },
];

/* ─── Rendered block (inside canvas / storefront) ─── */
function CB_Hero({ data, accent }) {
  return (
    <div className="cb-hero">
      <div>
        <div className="mono" style={{color:"var(--ink-soft)", marginBottom:12}}>EDITION · 2026</div>
        <h1>{data.title.split(data.emph).map((part, i, arr) => i < arr.length - 1
          ? <React.Fragment key={i}>{part}<em>{data.emph}</em></React.Fragment>
          : <React.Fragment key={i}>{part}</React.Fragment>)}</h1>
        <p>{data.subtitle}</p>
      </div>
      <div className="cover" />
    </div>
  );
}
function CB_Collection({ data }) {
  return (
    <div className="cb-collection">
      <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline"}}>
        <h2 className="cb-h2"><em>§</em> {data.heading}</h2>
        <div className="mono" style={{color:"var(--ink-soft)"}}>{data.count} {data.label}</div>
      </div>
      <div className="grid">
        {Array.from({length: data.count}).map((_, i) => (
          <div key={i} className="cb-item">
            <div className="thumb" style={{filter: `hue-rotate(${i*40}deg)`}} />
            <div className="info">
              <b>№ {String(i+1).padStart(2,"0")}</b>
              <span className="mono">JPG</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
function CB_Quote({ data }) {
  return (
    <div style={{padding:"42px 56px", borderTop:"1px solid var(--line)", textAlign:"center"}}>
      <p style={{fontFamily:"var(--serif)", fontStyle:"italic", fontSize:34, lineHeight:1.2, letterSpacing:"-.01em", margin:"0 auto 16px", maxWidth:"22ch", color:"var(--ink)"}}>
        "{data.text}"
      </p>
      <div className="mono" style={{color:"var(--ink-soft)"}}>{data.attribution}</div>
    </div>
  );
}
function CB_BuyBar({ data, onBuy }) {
  return (
    <div className="cb-buy">
      <div className="left">
        <b>{data.title}</b>
        <div style={{display:"flex", alignItems:"baseline", gap:10}}>
          <span className="price" style={{fontFamily:"var(--serif)", fontSize:30}}>KSh {data.price}</span>
          <span className="mono" style={{color:"var(--ink-soft)"}}>· one-time</span>
        </div>
        <div style={{fontSize:13, color:"var(--ink-soft)", marginTop:4}}>{data.subtitle}</div>
      </div>
      <div className="right">
        <button className="btn btn-outline">Preview</button>
        <button className="btn btn-primary btn-lg" onClick={onBuy}>
          <span style={{display:"inline-flex", alignItems:"center", gap:8}}>
            <span style={{width:18, height:18, background:"white", color:"#1B8B53", borderRadius:4, fontFamily:"var(--mono)", fontWeight:700, fontSize:9, display:"grid", placeItems:"center"}}>M</span>
            Buy via M-PESA <span className="arrow"/>
          </span>
        </button>
      </div>
    </div>
  );
}
function CB_Text({ data }) {
  return (
    <div style={{padding:"32px 56px", borderTop:"1px solid var(--line)"}}>
      <p style={{fontFamily:"var(--serif)", fontSize:20, lineHeight:1.5, color:"var(--ink)", maxWidth:"60ch", margin:0}}>
        {data.body}
      </p>
    </div>
  );
}
function CB_Gallery({ data }) {
  return (
    <div style={{padding:"24px 40px", borderTop:"1px solid var(--line)"}}>
      <div style={{display:"grid", gridTemplateColumns:`repeat(${data.count}, 1fr)`, gap:10}}>
        {Array.from({length: data.count}).map((_, i) => (
          <div key={i} style={{aspectRatio:"1", borderRadius:8, background:`linear-gradient(${i*60}deg, var(--accent), var(--ink))`}} />
        ))}
      </div>
    </div>
  );
}
function CB_Divider() {
  return <div style={{padding:"18px 40px"}}><div style={{height:1, background:"var(--line)"}}/></div>;
}

function renderBlock(block, onBuy) {
  const C = {
    hero: CB_Hero, collection: CB_Collection, quote: CB_Quote,
    buybar: CB_BuyBar, text: CB_Text, gallery: CB_Gallery, divider: CB_Divider,
  }[block.type];
  return <C data={block.data} onBuy={onBuy} />;
}

/* ═══════════════════════════════════════════════════════════════════════
   BUILDER
   ═══════════════════════════════════════════════════════════════════════ */
function Builder({ goto, canvasStyle, page, setPage }) {
  const [selectedId, setSelectedId] = useStateB(page[0]?.id);
  const [dragOver, setDragOver] = useStateB(null); // drop-zone index
  const [draggingType, setDraggingType] = useStateB(null);
  const [siteName, setSiteName] = useStateB("Field Notes Vol. 03");
  const [viewport, setViewport] = useStateB("desktop");

  const selected = page.find((b) => b.id === selectedId);

  const onDragStart = (type) => () => setDraggingType(type);
  const onDragEnd = () => { setDraggingType(null); setDragOver(null); };

  const onDropAt = (idx) => (e) => {
    e.preventDefault();
    if (!draggingType) return;
    const newBlock = {
      id: "b" + Date.now(),
      type: draggingType,
      data: { ...BLOCK_DEFS[draggingType].default },
    };
    const next = [...page];
    next.splice(idx, 0, newBlock);
    setPage(next);
    setSelectedId(newBlock.id);
    onDragEnd();
  };

  const deleteBlock = (id) => {
    setPage(page.filter((b) => b.id !== id));
    if (selectedId === id && page.length > 1) setSelectedId(page[0].id);
  };

  const updateSelected = (key, value) => {
    setPage(page.map((b) => b.id === selectedId ? { ...b, data: { ...b.data, [key]: value } } : b));
  };

  return (
    <div className="view-anim">
      <TopNav goto={goto} view="builder" />
      <div className="b-toolbar">
        <div className="row-flex">
          <span className="crumb">Workspace ▸ Collections ▸</span>
          <input
            className="title-edit"
            value={siteName}
            onChange={(e) => setSiteName(e.target.value)}
          />
          <span className="chip" style={{background:"color-mix(in srgb, var(--mint) 18%, var(--paper))", color:"var(--mint)"}}>● Saved</span>
        </div>
        <div className="row-flex" style={{gap:14}}>
          <div className="viewport-toggle">
            <button className={viewport==="desktop"?"active":""} onClick={() => setViewport("desktop")} title="Desktop">▭</button>
            <button className={viewport==="tablet"?"active":""} onClick={() => setViewport("tablet")} title="Tablet">▯</button>
            <button className={viewport==="mobile"?"active":""} onClick={() => setViewport("mobile")} title="Mobile">▮</button>
          </div>
          <button className="btn btn-outline btn-sm" onClick={() => goto("store")}>Preview</button>
          <button className="btn btn-primary btn-sm" onClick={() => goto("channels")}>
            Publish to channels <span className="arrow"/>
          </button>
        </div>
      </div>
      <div className="builder">
        {/* LEFT: blocks */}
        <aside className="b-sidebar">
          <div className="b-side-title">▸ Blocks</div>
          <div className="block-list">
            {Object.entries(BLOCK_DEFS).map(([type, def]) => (
              <div
                key={type}
                className="block-item"
                draggable
                onDragStart={onDragStart(type)}
                onDragEnd={onDragEnd}
              >
                <span className="block-icon">{def.glyph}</span>
                <span>{def.name}</span>
                <span className="spacer"/>
                <span style={{opacity:.4, fontSize:11}}>⋮⋮</span>
              </div>
            ))}
          </div>
          <div className="b-side-title" style={{marginTop:18}}>▸ Pages</div>
          <div className="block-list">
            <div className="block-item" style={{background:"color-mix(in srgb, var(--accent) 10%, var(--bg))", borderColor:"var(--accent)"}}>
              <span className="block-icon">●</span>
              <span>Home</span>
              <span className="spacer"/>
              <span className="mono" style={{fontSize:9}}>/</span>
            </div>
            <div className="block-item">
              <span className="block-icon" style={{background:"var(--line-strong)"}}>+</span>
              <span style={{color:"var(--ink-soft)"}}>Add page</span>
            </div>
          </div>
        </aside>

        {/* CENTER: canvas */}
        <div className="b-canvas-wrap" data-canvas={canvasStyle}>
          <div className="b-canvas" style={{
            maxWidth: viewport === "mobile" ? 380 : viewport === "tablet" ? 720 : 920
          }}>
            <div className="browser-bar">
              <span className="lights"><i/><i/><i/></span>
              <span className="url">https://{siteName.toLowerCase().replace(/\s+/g,"-")}.sema-ikutoke.so</span>
              <span style={{opacity:.5}}>· LIVE</span>
            </div>

            <DropZone index={0} active={dragOver===0} onDragOver={(e) => { e.preventDefault(); setDragOver(0); }} onDragLeave={() => setDragOver(null)} onDrop={onDropAt(0)} hasBlocks={page.length > 0} />

            {page.map((block, i) => (
              <React.Fragment key={block.id}>
                <div
                  className={"canvas-block " + (selectedId === block.id ? "selected" : "")}
                  onClick={() => setSelectedId(block.id)}
                >
                  {renderBlock(block, () => {})}
                  <button className="delete-btn" onClick={(e) => { e.stopPropagation(); deleteBlock(block.id); }}>×</button>
                </div>
                <DropZone
                  index={i+1}
                  active={dragOver===i+1}
                  onDragOver={(e) => { e.preventDefault(); setDragOver(i+1); }}
                  onDragLeave={() => setDragOver(null)}
                  onDrop={onDropAt(i+1)}
                  hasBlocks={true}
                />
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* RIGHT: inspector */}
        <aside className="b-inspector">
          {selected ? (
            <>
              <h3 className="insp-title">{BLOCK_DEFS[selected.type].name}</h3>
              <div className="insp-sub">Block · {selected.id}</div>
              {Object.entries(selected.data).map(([key, val]) => (
                <div key={key} className="insp-group">
                  <label>{key}</label>
                  {key === "body" || key === "text" ? (
                    <textarea value={val} onChange={(e) => updateSelected(key, e.target.value)} />
                  ) : typeof val === "number" ? (
                    <input type="number" value={val} onChange={(e) => updateSelected(key, +e.target.value)} />
                  ) : (
                    <input value={val} onChange={(e) => updateSelected(key, e.target.value)} />
                  )}
                </div>
              ))}
              <div className="insp-group">
                <label>Accent</label>
                <div className="swatch-row">
                  {["#E14118", "#1B8B53", "#5D2BD0", "#0E2740", "#C2421A"].map((c) => (
                    <div key={c} className="swatch" style={{background: c}} />
                  ))}
                </div>
              </div>
              <div className="insp-group">
                <label>Spacing</label>
                <input type="range" min="0" max="100" defaultValue="50" style={{width:"100%"}} />
              </div>
              <button className="btn btn-outline btn-sm" style={{justifyContent:"center", width:"100%"}} onClick={() => deleteBlock(selected.id)}>
                Remove block
              </button>
            </>
          ) : (
            <div className="muted" style={{textAlign:"center", padding:"40px 0"}}>
              <div className="mono" style={{marginBottom:8}}>NO SELECTION</div>
              Tap a block on the canvas to edit.
            </div>
          )}
        </aside>
      </div>
    </div>
  );
}

function DropZone({ active, onDragOver, onDragLeave, onDrop, hasBlocks, index }) {
  return (
    <div
      className={"drop-zone " + (active ? "over" : "")}
      onDragOver={onDragOver}
      onDragLeave={onDragLeave}
      onDrop={onDrop}
      style={!hasBlocks && index === 0 ? {height:160, margin:"24px 16px"} : {}}
    >
      {active ? "Drop here" : (index === 0 && !hasBlocks ? "Drag a block to start" : "+ drop block")}
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════
   STOREFRONT (the published site, with Buy)
   ═══════════════════════════════════════════════════════════════════════ */
function Storefront({ goto, page, onBuy }) {
  return (
    <div className="view-anim">
      <TopNav goto={goto} view="store" />
      <div style={{padding:"22px 36px 4px", borderBottom:"1px solid var(--line)", display:"flex", justifyContent:"space-between", alignItems:"center"}}>
        <div className="mono" style={{color:"var(--ink-soft)"}}>
          ▸ kamau.sema-ikutoke.so · viewing as buyer · ● LIVE
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => goto("builder")}>← back to editor</button>
      </div>
      <div style={{maxWidth: 960, margin: "32px auto 96px", background: "var(--paper)", border:"1px solid var(--line)", borderRadius:18, overflow:"hidden", boxShadow:"0 30px 80px -30px rgba(0,0,0,.18)"}}>
        <div className="browser-bar" style={{padding:"10px 14px", borderBottom:"1px solid var(--line)", display:"flex", alignItems:"center", gap:10, fontFamily:"var(--mono)", fontSize:11, color:"var(--ink-faint)"}}>
          <span style={{display:"flex", gap:5}}><i style={{width:9, height:9, borderRadius:"50%", background:"var(--line-strong)", display:"inline-block"}}/><i style={{width:9, height:9, borderRadius:"50%", background:"var(--line-strong)", display:"inline-block"}}/><i style={{width:9, height:9, borderRadius:"50%", background:"var(--line-strong)", display:"inline-block"}}/></span>
          <span style={{flex:1, background:"var(--bg)", padding:"4px 10px", borderRadius:6}}>https://kamau.sema-ikutoke.so</span>
        </div>
        {page.map((block, i) => (
          <React.Fragment key={block.id}>
            {renderBlock(block, onBuy)}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════
   CHECKOUT — variants: drawer / modal / page
   ═══════════════════════════════════════════════════════════════════════ */
function useMpesaFlow(onSuccess) {
  const [stage, setStage] = useStateB("entry"); // entry → sending → awaiting → success
  const [phone, setPhone] = useStateB("712 345 678");
  const [code, setCode] = useStateB("+254");

  const submit = () => {
    setStage("sending");
    setTimeout(() => setStage("awaiting"), 900);
    setTimeout(() => setStage("success"), 3400);
  };

  const reset = () => setStage("entry");

  return { stage, phone, code, setPhone, setCode, submit, reset };
}

function MpesaFlow({ flow, item, onClose, onSuccess }) {
  const { stage, phone, code, setPhone, setCode, submit } = flow;

  if (stage === "entry") {
    return (
      <>
        <div className="row-flex">
          <span className="chip mint">M-PESA</span>
          <span className="mono" style={{color:"var(--ink-soft)"}}>STK Push</span>
        </div>
        <h3>Enter the phone to charge.</h3>
        <p className="muted" style={{fontSize:14, margin:0}}>
          We'll send an M-PESA prompt to this number. You'll have 60 seconds to approve it.
        </p>
        <div className="field">
          <label>Phone number</label>
          <div className="phone-wrap">
            <select value={code} onChange={(e) => setCode(e.target.value)}>
              <option>+254</option><option>+255</option><option>+256</option>
            </select>
            <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="712 345 678" />
          </div>
        </div>
        <div className="receipt" style={{background:"var(--paper)"}}>
          <div className="row"><span>{item.name}</span><span>KSh {item.price}</span></div>
          <div className="row"><span>M-PESA fee</span><span>KSh 0</span></div>
          <div className="row total"><span>Total</span><span>KSh {item.price}</span></div>
        </div>
        <button className="btn btn-primary btn-lg" onClick={submit} style={{justifyContent:"center"}}>
          Send prompt to my phone <span className="arrow"/>
        </button>
        <div className="mono" style={{fontSize:10, color:"var(--ink-faint)", textAlign:"center"}}>
          By tapping you agree to sema ikutoke's terms · Safaricom M-PESA Daraja
        </div>
      </>
    );
  }
  if (stage === "sending") {
    return (
      <div className="checkout-step">
        <div className="phone-pulse">📲</div>
        <h3>Sending to your phone…</h3>
        <p>Reaching out to {code} {phone}.</p>
      </div>
    );
  }
  if (stage === "awaiting") {
    return (
      <div className="checkout-step">
        <div className="phone-pulse" style={{background:"var(--accent)"}}>↗</div>
        <h3>Approve on your phone.</h3>
        <p>Enter your M-PESA PIN on the prompt we sent to <b>{code} {phone}</b>.</p>
        <div className="receipt" style={{background:"color-mix(in srgb, var(--accent) 8%, var(--paper))", borderColor:"var(--accent)", width:"100%"}}>
          <div className="row"><span>Prompt ref</span><span>RST-9F2-{Math.floor(Math.random()*9000+1000)}</span></div>
          <div className="row"><span>Amount</span><span>KSh {item.price}</span></div>
          <div className="row"><span>Expires</span><span>60 s</span></div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
      </div>
    );
  }
  // success
  return (
    <div className="checkout-step">
      <div className="phone-pulse" style={{background:"var(--mint)"}}>✓</div>
      <h3>You've got it.</h3>
      <p>Receipt sent to your email. The collection is downloading.</p>
      <div className="receipt" style={{width:"100%"}}>
        <div className="row"><span>RECEIPT</span><span>RST-{Date.now().toString().slice(-6)}</span></div>
        <div className="row"><span>{item.name}</span><span>KSh {item.price}</span></div>
        <div className="row"><span>Method</span><span>M-PESA · {code} {phone}</span></div>
        <div className="row total"><span>Paid</span><span>KSh {item.price}</span></div>
      </div>
      <div className="row-flex" style={{gap:10}}>
        <button className="btn btn-outline" onClick={onClose}>Close</button>
        <button className="btn btn-primary" onClick={onSuccess}>
          Download collection <span className="arrow"/>
        </button>
      </div>
    </div>
  );
}

function CheckoutDrawer({ item, onClose, onSuccess }) {
  const flow = useMpesaFlow();
  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <div className="drawer">
        <button className="drawer-close" onClick={onClose}>×</button>
        <div className="mono" style={{color:"var(--ink-soft)"}}>§ 04 / Checkout · Drawer</div>
        <MpesaFlow flow={flow} item={item} onClose={onClose} onSuccess={onSuccess} />
      </div>
    </>
  );
}

function CheckoutModal({ item, onClose, onSuccess }) {
  const flow = useMpesaFlow();
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{position:"relative"}}>
        <button className="modal-close" onClick={onClose}>×</button>
        <div className="mono" style={{color:"var(--ink-soft)"}}>§ 04 / Checkout · Modal</div>
        <MpesaFlow flow={flow} item={item} onClose={onClose} onSuccess={onSuccess} />
      </div>
    </div>
  );
}

function CheckoutPage({ item, goto, onSuccess }) {
  const flow = useMpesaFlow();
  return (
    <div className="view-anim">
      <TopNav goto={goto} view="checkout" />
      <div className="checkout-page">
        <div className="checkout-summary">
          <div className="blob" />
          <div style={{position:"relative", zIndex:1, display:"flex", flexDirection:"column", gap:24, height:"100%"}}>
            <div className="brand-mini">sema ikutoke — checkout</div>
            <div className="mono" style={{color:"color-mix(in srgb, var(--paper) 60%, transparent)"}}>§ 04 / Order</div>
            <div className="cs-item">
              <div className="cover" />
              <div className="meta">
                <small>Kamau Studio</small>
                <b>{item.name}</b>
                <span className="mono" style={{color:"color-mix(in srgb, var(--paper) 50%, transparent)"}}>
                  23 photos · 14 essays · 42 MB
                </span>
              </div>
              <div className="price">KSh {item.price}</div>
            </div>
            <div className="cs-totals" style={{marginTop:"auto"}}>
              <div className="row"><span style={{opacity:.7}}>Subtotal</span><span>KSh {item.price}</span></div>
              <div className="row"><span style={{opacity:.7}}>M-PESA fee</span><span>KSh 0</span></div>
              <div className="row"><span style={{opacity:.7}}>Tax (16% VAT)</span><span>included</span></div>
              <div className="row total"><span>Total</span><span>KSh {item.price}</span></div>
            </div>
            <div className="mono" style={{color:"color-mix(in srgb, var(--paper) 50%, transparent)", fontSize:10}}>
              Secured by Safaricom M-PESA Daraja · Settled in 11 seconds
            </div>
          </div>
        </div>
        <div className="checkout-form">
          <h2>Pay with M-PESA.</h2>
          <div className="method-card">
            <div className="mpesa-mark">M·PESA</div>
            <div className="meta">
              <b>M-PESA</b>
              <small>STK push to your phone — no card, no fuss</small>
            </div>
            <div className="check">✓</div>
          </div>
          <MpesaFlow flow={flow} item={item} onClose={() => goto("store")} onSuccess={onSuccess} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Builder, Storefront, CheckoutDrawer, CheckoutModal, CheckoutPage,
  DEFAULT_PAGE, BLOCK_DEFS,
});
