// Monteforma — Quote, Materials, Finishes
const { useState: useS1, useEffect: useE1, useMemo: useM1, useRef: useR1 } = React;

function Quote() {
  const [file, setFile] = useS1(null);
  const [over, setOver] = useS1(false);
  const [material, setMaterial] = useS1('PLA');
  const [infill, setInfill] = useS1(20);
  const [layer, setLayer] = useS1(0.2);
  const [qty, setQty] = useS1(1);
  const [finish, setFinish] = useS1('Standard');
  const inputRef = useR1(null);

  // Real rates: 25 €/kg for PLA/PETG/ABS, 40 €/kg for TPU
  const matInfo = {
    PLA:  { price: 25, density: 1.24 },
    PETG: { price: 25, density: 1.27 },
    ABS:  { price: 25, density: 1.04 },
    TPU:  { price: 40, density: 1.21 },
  };
  // mock volume in cm^3 — use file size if file given, else fallback
  const volume = useM1(() => {
    if (!file) return 28;
    return Math.max(8, Math.min(220, file.size / 18000));
  }, [file]);

  // Estimated grams: walls + infill share of bounding volume.
  const grams = useM1(() => {
    const fill = infill / 100 * 0.7 + 0.3; // ~30% perimeter+top/bottom + infill share
    return volume * matInfo[material].density * fill;
  }, [volume, infill, material]);

  // Hours: rough — slower at fine layers, faster at coarse.
  const hours = useM1(() => {
    return (volume * 0.045) / (layer * 4); // tuned to feel right
  }, [volume, layer]);

  const price = useM1(() => {
    const materialCost = grams / 1000 * matInfo[material].price;
    const machineCost = hours * 1.5; // small machine-time fee
    const finishCost = finish === 'Sanded' ? 4 : finish === 'Painted' ? 8 : 0;
    const setup = 4;
    const unit = materialCost + machineCost + finishCost;
    const total = (unit + setup) * qty;
    return Math.max(6, total);
  }, [grams, hours, material, finish, qty]);

  const onDrop = (e) => {
    e.preventDefault(); setOver(false);
    const f = e.dataTransfer.files?.[0]; if (f) setFile(f);
  };
  const onPick = (e) => { const f = e.target.files?.[0]; if (f) setFile(f); };

  return (
    <section id="quote" className="quote">
      <div className="wrap">
        <div className="sec-head reveal">
          <div>
            <span className="eyebrow">— Instant estimate</span>
            <h2 className="h-section" style={{color:'var(--bg)'}}>Drop a file.<br/>Get a price.</h2>
          </div>
          <p className="sec-head__r lede" style={{color:'#C9C0B5'}}>
            Drag and drop your STL, STEP, OBJ or 3MF for an automatic estimate based on volume,
            material and finish. We confirm by hand within a few hours.
          </p>
        </div>

        <div className="quote-grid reveal">
          <div
            className={`drop ${over ? 'is-over' : ''} ${file ? 'has-file' : ''}`}
            onDragOver={(e)=>{e.preventDefault(); setOver(true);}}
            onDragLeave={()=>setOver(false)}
            onDrop={onDrop}
            onClick={()=>inputRef.current?.click()}
            role="button" tabIndex={0}
            style={{cursor:'pointer'}}
          >
            <input ref={inputRef} type="file" accept=".stl,.step,.stp,.obj,.3mf" onChange={onPick} style={{display:'none'}} />
            {!file ? (
              <div className="drop__hint">
                <div style={{fontSize: 48, lineHeight: 1, color:'#C9C0B5'}}>⌬</div>
                <h3>Drop your model here</h3>
                <p>or click to browse</p>
                <div className="formats">.stl · .step · .obj · .3mf · max 50MB</div>
              </div>
            ) : (
              <div className="drop__file">
                <div className="drop__filename">FILE LOADED · {file.name}</div>
                <div style={{fontFamily:'var(--font-display)', fontSize: 48, fontWeight: 600, letterSpacing:'-0.02em', lineHeight: 0.95}}>
                  {volume.toFixed(1)} cm³<br/>
                  <span style={{fontSize:18, color:'#B8AFA4', fontWeight: 400, letterSpacing: 0}}>estimated print volume</span>
                </div>
                <button className="btn btn-ghost" style={{color:'#fff', marginTop: 12}} onClick={(e)=>{e.stopPropagation(); setFile(null);}}>Replace file</button>
              </div>
            )}
          </div>

          <div className="quote-form">
            <div className="field">
              <label>Material</label>
              <div className="chips">
                {Object.keys(matInfo).map(m => (
                  <button key={m} className={`chip ${material===m?'is-on':''}`} onClick={()=>setMaterial(m)}>{m}</button>
                ))}
              </div>
            </div>

            <div className="field">
              <label>Finish</label>
              <div className="chips">
                {['Standard', 'Sanded', 'Painted'].map(f => (
                  <button key={f} className={`chip ${finish===f?'is-on':''}`} onClick={()=>setFinish(f)}>{f}</button>
                ))}
              </div>
            </div>

            <div className="field-row">
              <div className="field">
                <label>Infill <span className="mono" style={{color:'var(--green-soft)'}}>{infill}%</span></label>
                <input className="slider-input" type="range" min={5} max={100} step={5} value={infill} onChange={e=>setInfill(+e.target.value)} />
              </div>
              <div className="field">
                <label>Layer height <span className="mono" style={{color:'var(--green-soft)'}}>{layer.toFixed(2)} mm</span></label>
                <input className="slider-input" type="range" min={0.08} max={0.28} step={0.04} value={layer} onChange={e=>setLayer(+e.target.value)} />
              </div>
            </div>

            <div className="field">
              <label>Quantity</label>
              <div className="chips">
                {[1,5,10,25,50,100].map(n => (
                  <button key={n} className={`chip ${qty===n?'is-on':''}`} onClick={()=>setQty(n)}>{n}{n===1?' pc':' pcs'}</button>
                ))}
              </div>
            </div>

            <div className="estimate">
              <div>
                <div className="eyebrow" style={{color:'#B8AFA4', marginBottom: 8}}>Estimate</div>
                <div className="estimate__price">
                  <span className="estimate__cur">€</span>{price.toFixed(0)}
                </div>
              </div>
              <div className="estimate__meta" style={{textAlign:'right'}}>
                <div><b>{material}</b> · {finish.toLowerCase()}</div>
                <div>{grams.toFixed(0)} g · {infill}% infill · {layer.toFixed(2)} mm</div>
                <div>{qty} pc{qty>1?'s':''} · ~{(hours*qty).toFixed(1)} h print</div>
              </div>
            </div>

            <a href="#contact" className="btn btn-light btn-arrow" style={{alignSelf:'flex-start'}}>Send for confirmation</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function Materials() {
  const data = {
    PLA: {
      tag: 'Most popular',
      tagline: 'Easy, sharp, eco-friendly.',
      desc: 'Plant-based, low-warp and capable of crisp surface detail. Ideal for decorative pieces, models and indoor parts. Avoid in hot cars or direct summer sun.',
      best: ['Decorative', 'Models', 'Toys', 'Prototypes'],
      stats: { Strength: 55, Heat: 25, Flex: 20, Detail: 90, Outdoor: 30 },
    },
    PETG: {
      tag: 'All-rounder',
      tagline: 'Tough, weatherable, food-safe.',
      desc: 'Strong and slightly flexible with good chemical and UV resistance. Our default for functional parts, brackets, enclosures and anything destined to live outdoors.',
      best: ['Functional', 'Outdoor', 'Brackets', 'Containers'],
      stats: { Strength: 75, Heat: 60, Flex: 45, Detail: 70, Outdoor: 80 },
    },
    ABS: {
      tag: 'Engineering',
      tagline: 'Heat-resistant, machinable.',
      desc: 'High temperature resistance and impact strength. Great for under-the-hood automotive parts, electronics enclosures and anything that gets sanded, drilled or bonded with solvent.',
      best: ['Automotive', 'Enclosures', 'Tooling', 'Jigs'],
      stats: { Strength: 80, Heat: 90, Flex: 50, Detail: 65, Outdoor: 60 },
    },
    TPU: {
      tag: 'Flexible',
      tagline: 'Bendy, grippy, abrasion-proof.',
      desc: 'A rubber-like filament for gaskets, phone bumpers, drone feet, grips and anything that needs to absorb impact or stretch without cracking.',
      best: ['Gaskets', 'Grips', 'Bumpers', 'Wearables'],
      stats: { Strength: 50, Heat: 50, Flex: 95, Detail: 55, Outdoor: 70 },
    },
  };
  const [active, setActive] = useS1('PLA');
  const m = data[active];
  return (
    <section id="materials" className="materials">
      <div className="wrap">
        <div className="sec-head reveal">
          <div>
            <span className="eyebrow">— Pick the right plastic</span>
            <h2 className="h-section">Four<br/>materials.</h2>
          </div>
          <p className="sec-head__r lede">
            Each filament has a personality. Tap one to see what it's good at — or tell us about
            the part and we'll suggest the right material for the job.
          </p>
        </div>

        <div className="mat-tabs reveal">
          {Object.keys(data).map(k => (
            <button key={k} className={`mat-tab ${active===k?'is-on':''}`} onClick={()=>setActive(k)}>
              {k}
              <small>{data[k].tag}</small>
            </button>
          ))}
        </div>

        <div className="mat-panel">
          <div>
            <div className="tag">{m.tag}</div>
            <h3>{m.tagline}</h3>
            <p>{m.desc}</p>
            <div className="mat-best">
              {m.best.map(b => <span key={b}>{b}</span>)}
            </div>
          </div>
          <div className="mat-stats">
            {Object.entries(m.stats).map(([k, v]) => (
              <div key={k} className="stat-row">
                <div className="label">{k}</div>
                <div className="bar"><i style={{width: v + '%'}} /></div>
                <div className="value">{v}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Finishes() {
  const swatches = [
    { name: 'Black',        code: 'PLA Basic',  bg: '#15130F', light: false },
    { name: 'Matte Black',  code: 'PLA Matte',  bg: '#1F1C18', light: false },
    { name: 'Light Grey',   code: 'PLA Basic',  bg: '#C8C7C4', light: true  },
    { name: 'Silver',       code: 'PLA Silk',   bg: 'linear-gradient(135deg, #C2C3C7, #E2E3E5 45%, #A8AAAE)', light: true },
    { name: 'Cream',        code: 'PLA Basic',  bg: '#EFE6D2', light: true  },
    { name: 'Red',          code: 'PLA Basic',  bg: '#B83025', light: false },
    { name: 'Orange',       code: 'PLA Basic',  bg: '#E08725', light: false },
    { name: 'Yellow',       code: 'PLA Basic',  bg: '#E8C233', light: true  },
    { name: 'Blue',         code: 'PETG HF',    bg: '#1F4F7C', light: false },
    { name: 'Brown',        code: 'PLA Basic',  bg: '#5A3A22', light: false },
    { name: 'Light Brown',  code: 'PLA Basic',  bg: '#A6794A', light: false },
  ];
  return (
    <section id="finishes" className="finishes">
      <div className="wrap">
        <div className="sec-head reveal">
          <div>
            <span className="eyebrow">— Colour & finish</span>
            <h2 className="h-section">A good<br/>selection<br/>of colours.</h2>
          </div>
          <p className="sec-head__r lede">
            Most filament we use comes from Bambu Lab's range — clean, consistent and well-tested.
            Below: the colours we keep on the shelf. If you need something specific, ask.
          </p>
        </div>
        <div className="swatch-grid reveal">
          {swatches.map(s => (
            <div key={s.name} className={`swatch ${s.light?'dark-text':''}`} style={{background: s.bg}}>
              <div className="swatch__label">
                <span>{s.name}</span>
                <span>{s.code}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Quote, Materials, Finishes });
