// ── OUR METHOD PAGE ───────────────────────────────────
const API_BASE = 'https://metera-api.holovchanskyi.workers.dev';

function truncate(text, max = 160) {
  if (!text || text.length <= max) return text || '';
  const trimmed = text.slice(0, max);
  return trimmed.slice(0, trimmed.lastIndexOf(' ')) + '…';
}

function MethodPage({ navigate, tweaks }) {
  const gold = tweaks.accentColor;
  useReveal();

  const steps = [
    {
      num: '01', title: 'Listen First',
      imgUrl: null,
      body: "Before anything is built, we start by listening. We take the time to deeply understand your business, your team, and the challenges that may be limiting your growth. This includes analyzing your current processes, identifying gaps, and uncovering opportunities that are often overlooked.\n\nWithout this level of clarity, even the best strategies can fall short. Our goal is to build a strong foundation based on real insight — not assumptions — so every decision moving forward is intentional, relevant, and aligned with your business objectives.",
    },
    {
      num: '02', title: 'Build the System',
      imgUrl: null,
      body: "Once we have clarity, we move into building the system that will support and scale your sales efforts. This is where strategy turns into structure. We design and implement a complete sales infrastructure tailored specifically to your business — not a generic template, but a system aligned with how you operate, sell, and grow.\n\nThis includes setting up and optimizing your CRM, defining a clear and logical pipeline, and creating structured lead follow-up workflows. We eliminate unnecessary steps, reduce friction, and create consistency across your entire operation.\n\nA key focus is usability. Your system should not only be powerful but also simple for your team to adopt and execute daily. We integrate automation where it adds value — reducing manual tasks, improving response times, and ensuring no opportunity is missed.",
    },
    {
      num: '03', title: 'Drive the Results',
      imgUrl: null,
      body: "With the right system in place, the focus shifts to execution, performance, and continuous improvement. This is where strategy becomes measurable outcomes. We work alongside your team to ensure the system is not only implemented but actively used, optimized, and refined over time.",
      bullets: [
        'Execute strategy clearly to drive measurable results',
        'Track metrics consistently to identify growth opportunities',
        'Optimize processes continuously for better efficiency outcomes',
        'Remove bottlenecks to maintain smooth pipeline flow',
        'Use data insights for smarter business decisions',
        'Strengthen execution through accountability and team alignment',
      ],
    },
  ];

  return (
    <div>
      <PageHero
        eyebrow="The Process"
        title="Our Method"
        subhead="A Structured Approach to Predictable Growth"
        imgUrl="assets/images/method/banner.png"
        accentColor={gold}
      />

      {/* Pull quote */}
      <section style={{ background:'var(--paper-warm)', padding:'clamp(64px,8vw,96px) 0' }}>
        <div style={{ maxWidth:'800px', margin:'0 auto', padding:'0 clamp(24px,5vw,80px)', textAlign:'center' }} className="reveal">
          <div style={{ width:'44px', height:'1px', background:gold, margin:'0 auto 28px' }} />
          <blockquote style={{ fontFamily:'var(--serif)', fontStyle:'italic', fontSize:'clamp(20px,2.5vw,30px)', fontWeight:'300', lineHeight:1.55, color:'var(--ink)' }}>
            "It's built through clarity, structure, and consistent execution. Our method is designed to remove guesswork and replace it with a proven, repeatable process that drives results. Every step is intentional. Every action is aligned."
          </blockquote>
          <div style={{ width:'44px', height:'1px', background:gold, margin:'28px auto 0' }} />
        </div>
      </section>

      {/* Timeline */}
      <section style={{ background:'var(--ink)', padding:'clamp(80px,10vw,130px) clamp(24px,5vw,80px)', position:'relative' }}>
        <div style={{ maxWidth:'1000px', margin:'0 auto', position:'relative' }}>
          {/* Vertical spine */}
          <div style={{ position:'absolute', left:'50%', top:0, bottom:0, width:'1px', background:'rgba(184,150,46,0.2)', transform:'translateX(-50%)', pointerEvents:'none' }} />

          {steps.map((s, i) => {
            const isLeft = i % 2 === 0;
            return (
              <div key={i} className="reveal method-grid" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'clamp(32px,5vw,72px)', marginBottom: i < steps.length-1 ? 'clamp(48px,7vw,96px)' : 0, position:'relative' }}>
                {/* Dot on spine */}
                <div style={{ position:'absolute', left:'50%', top:'36px', width:'10px', height:'10px', border:`1px solid ${gold}`, background:'var(--ink)', transform:'translateX(-50%)', zIndex:2 }} />

                {/* Left cell */}
                <div>
                  {isLeft ? (
                    <div style={{ border:`1px solid ${i===1?'rgba(184,150,46,0.2)':'rgba(184,150,46,0.12)'}`, background: i===1?'rgba(184,150,46,0.06)':'rgba(248,245,239,0.03)', padding:'clamp(32px,4vw,48px)' }}>
                      <p style={{ fontFamily:'var(--serif)', fontSize:'clamp(56px,7vw,90px)', fontWeight:'300', lineHeight:1, color:'rgba(184,150,46,0.08)', letterSpacing:'-0.02em', marginBottom:'-12px', marginLeft:'-4px' }}>{s.num}</p>
                      <p className="t-eyebrow" style={{ color:gold, marginBottom:'10px' }}>Step {s.num}</p>
                      <h2 style={{ fontFamily:'var(--serif)', fontSize:'clamp(22px,2.5vw,32px)', fontWeight:'300', color:'var(--paper)', lineHeight:1.2, marginBottom:'16px' }}>{s.title}</h2>
                      <div style={{ width:'32px', height:'1px', background:gold, marginBottom:'18px' }} />
                      {s.body.split('\n\n').map((para, j) => (
                        <p key={j} className="t-body" style={{ fontSize:'13px', color:'rgba(248,245,239,0.58)', marginBottom:'12px', lineHeight:1.8 }}>{para}</p>
                      ))}
                      {s.bullets && (
                        <div style={{ marginTop:'8px', display:'flex', flexDirection:'column', gap:'8px' }}>
                          {s.bullets.map((b, j) => (
                            <div key={j} style={{ display:'flex', alignItems:'flex-start', gap:'12px' }}>
                              <span style={{ width:'16px', height:'1px', background:gold, marginTop:'9px', flexShrink:0 }} />
                              <span className="t-body" style={{ fontSize:'13px', color:'rgba(248,245,239,0.58)', lineHeight:1.7 }}>{b}</span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  ) : <div />}
                </div>

                {/* Right cell */}
                <div>
                  {!isLeft ? (
                    <div style={{ border:`1px solid ${i===1?'rgba(184,150,46,0.2)':'rgba(184,150,46,0.12)'}`, background: i===1?'rgba(184,150,46,0.06)':'rgba(248,245,239,0.03)', padding:'clamp(32px,4vw,48px)' }}>
                      <p style={{ fontFamily:'var(--serif)', fontSize:'clamp(56px,7vw,90px)', fontWeight:'300', lineHeight:1, color:'rgba(184,150,46,0.08)', letterSpacing:'-0.02em', marginBottom:'-12px', marginLeft:'-4px' }}>{s.num}</p>
                      <p className="t-eyebrow" style={{ color:gold, marginBottom:'10px' }}>Step {s.num}</p>
                      <h2 style={{ fontFamily:'var(--serif)', fontSize:'clamp(22px,2.5vw,32px)', fontWeight:'300', color:'var(--paper)', lineHeight:1.2, marginBottom:'16px' }}>{s.title}</h2>
                      <div style={{ width:'32px', height:'1px', background:gold, marginBottom:'18px' }} />
                      {s.body.split('\n\n').map((para, j) => (
                        <p key={j} className="t-body" style={{ fontSize:'13px', color:'rgba(248,245,239,0.58)', marginBottom:'12px', lineHeight:1.8 }}>{para}</p>
                      ))}
                      {s.bullets && (
                        <div style={{ marginTop:'8px', display:'flex', flexDirection:'column', gap:'8px' }}>
                          {s.bullets.map((b, j) => (
                            <div key={j} style={{ display:'flex', alignItems:'flex-start', gap:'12px' }}>
                              <span style={{ width:'16px', height:'1px', background:gold, marginTop:'9px', flexShrink:0 }} />
                              <span className="t-body" style={{ fontSize:'13px', color:'rgba(248,245,239,0.58)', lineHeight:1.7 }}>{b}</span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  ) : <div />}
                </div>
              </div>
            );
          })}
        </div>
        <style>{`@media(max-width:640px){.method-grid{grid-template-columns:1fr!important;}}`}</style>
      </section>

      <CTABand navigate={navigate} accentColor={gold} heading="Ready to follow the method?" sub="Every step is intentional. Every action is aligned. Let's get started." />
    </div>
  );
}

// ── FAQS PAGE ─────────────────────────────────────────
function FAQsPage({ navigate, tweaks }) {
  const gold = tweaks.accentColor;
  const [open, setOpen] = React.useState(null);
  useReveal();

  const faqs = [
    { q:'What is Metera Collective?', a:'Metera Collective is a fractional sales development firm founded by Brenda Richey. We help founder-led businesses and small companies build structured sales systems, CRM processes, and AI-powered workflows that convert more leads and create predictable revenue growth.' },
    { q:'What does a fractional sales development firm do?', a:'A fractional sales development firm gives you access to experienced sales leadership without the cost of a full-time hire. At Metera Collective, we design and implement scalable sales systems, automate repetitive tasks using AI, and build processes that help your team consistently generate and convert leads.' },
    { q:'Who is Metera Collective for?', a:"Metera Collective is built for founder-led businesses, startups, and small teams that are ready to move beyond inconsistent sales. If you're looking to implement AI, streamline your CRM, and build a predictable revenue engine, Metera is designed for you." },
    { q:'How is Metera different from a sales coach or consultant?', a:"Unlike traditional sales coaches or consultants who focus on advice, Metera Collective focuses on execution. We don't just guide you — we build your sales infrastructure, implement AI tools, and create systems your team can actually use day-to-day." },
    { q:'What CRM platforms does Metera Collective work with?', a:'We work with leading CRM platforms such as HubSpot, Salesforce, and other modern tools. More importantly, we customize your CRM with AI-powered automations and workflows tailored to your specific sales process.' },
    { q:'How quickly will I see results?', a:'Most clients begin to see improvements in clarity, lead tracking, and process efficiency within the first few weeks. Measurable growth in conversions and revenue typically follows as AI systems and workflows are fully implemented.' },
    { q:'Does my business need to be a certain size?', a:'No specific size is required. However, Metera Collective is best suited for businesses that already have some traction and are ready to scale using structured systems and AI-driven processes.' },
    { q:'How does Metera Collective use AI?', a:'We use AI to automate lead qualification, follow-ups, data entry, and reporting. AI also helps identify patterns in your pipeline, prioritize high-value opportunities, and ensure no lead falls through the cracks.' },
    { q:'What is a sales system and why does my business need one?', a:'A sales system is a structured process that guides how leads are captured, nurtured, and converted into customers. Without a system, sales remain inconsistent. With the right AI-powered system, your business gains predictability, efficiency, and scalable growth.' },
    { q:'How do I get started?', a:'Getting started is simple. We begin with a discovery session to understand your current sales process, goals, and gaps. From there, we design and implement a tailored, AI-powered sales system that fits your business.' },
  ];

  return (
    <div>
      <PageHero
        eyebrow="Questions & Answers"
        title="Frequently Asked Questions"
        subhead="Everything you need to know about working with Metera Collective."
        imgUrl="assets/images/faq/banner.png"
        accentColor={gold}
      />

      <section style={{ background:'var(--paper)', padding:'clamp(64px,8vw,100px) 0' }}>
        <div style={{ maxWidth:'800px', margin:'0 auto', padding:'0 clamp(24px,5vw,80px)' }}>
          {faqs.map((f, i) => (
            <div key={i} className="reveal" style={{ borderBottom:'1px solid var(--fog)' }}>
              <button onClick={() => setOpen(open===i ? null : i)} style={{ width:'100%', display:'flex', justifyContent:'space-between', alignItems:'center', gap:'20px', padding:'clamp(20px,2.5vw,28px) 0', background:'none', border:'none', cursor:'pointer', textAlign:'left' }} aria-expanded={open===i}>
                <span style={{ fontFamily:'var(--serif)', fontSize:'clamp(17px,2vw,22px)', fontWeight:'400', color:'var(--ink)', lineHeight:1.3 }}>{f.q}</span>
                <span style={{ flexShrink:0, width:'28px', height:'28px', border:`1px solid ${open===i?gold:'var(--fog)'}`, display:'flex', alignItems:'center', justifyContent:'center', color:open===i?gold:'var(--taupe)', transition:'border-color 0.2s,color 0.2s,transform 0.3s', transform:open===i?'rotate(45deg)':'none', fontSize:'18px', lineHeight:1 }}>+</span>
              </button>
              <div style={{ maxHeight:open===i?'400px':'0', overflow:'hidden', transition:'max-height 0.45s cubic-bezier(0.16,1,0.3,1)' }}>
                <p className="t-body" style={{ paddingBottom:'26px', paddingRight:'52px', color:'var(--taupe)', lineHeight:'1.8' }}>{f.a}</p>
              </div>
            </div>
          ))}
        </div>
      </section>

      <CTABand navigate={navigate} accentColor={gold} heading="Still have questions?" sub="We'd love to talk through your specific situation. Book a free discovery call." />
    </div>
  );
}

// ── BLOGS PAGE ────────────────────────────────────────
function BlogsPage({ navigate, tweaks }) {
  const gold = tweaks.accentColor;
  const [hovered, setHovered] = React.useState(null);
  const [posts, setPosts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    fetch(`${API_BASE}/api/posts`)
      .then(r => r.json())
      .then(data => { setPosts(Array.isArray(data) ? data : []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  useReveal();

  if (loading) return <div style={{ padding: '120px 0', textAlign: 'center', fontFamily: 'var(--sans)', color: 'var(--taupe)' }}>Loading…</div>;

  const featuredPosts = posts.filter(p => p.featured === 1 || p.featured === true);
  const restPosts = posts.filter(p => !(p.featured === 1 || p.featured === true));

  return (
    <div>
      <PageHero
        eyebrow="Insights & Strategy"
        title="Our Blog"
        subhead="Practical strategies, real-world sales lessons, and AI-driven insights to help you build a smarter, more scalable business."
        imgUrl="assets/images/blog/banner.png"
        accentColor={gold}
      />

      <section style={{ background:'var(--paper)', padding:'clamp(64px,8vw,100px) 0' }}>
        <div style={{ maxWidth:'1280px', margin:'0 auto', padding:'0 clamp(24px,5vw,80px)' }}>
          {posts.length === 0 ? (
            <div style={{ padding: '80px 0', textAlign: 'center', fontFamily: 'var(--serif)', fontSize: '22px', color: 'var(--taupe)' }}>No posts yet.</div>
          ) : (
            <>
              {featuredPosts.length > 0 && (
                <section style={{ padding: '100px 40px 60px', maxWidth: 1200, margin: '0 auto' }}>
                  <div style={{ display: 'inline-block', padding: '10px 32px', background: 'var(--gold)', border: '1px solid var(--gold-dark)', color: 'var(--paper)', fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: '500', letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: 48 }}>Featured</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                    {featuredPosts.map((featured, idx) => (
                      <div
                        key={featured.id}
                        onClick={() => navigate('post/' + featured.id)}
                        style={{ cursor: 'pointer', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60, alignItems: 'center', border: '1px solid var(--fog)', padding: '40px', marginTop: idx === 0 ? 0 : '-2px' }}
                        className="two-col"
                      >
                        <div style={{ aspectRatio: '4/3', background: 'var(--fog)', position: 'relative', overflow: 'hidden' }}>
                          {featured.image_url ? (
                            <img
                              src={featured.image_url}
                              alt={featured.title}
                              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center' }}
                            />
                          ) : (
                            <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--taupe)', fontFamily: 'var(--serif)', fontSize: 20, fontStyle: 'italic' }}>Featured Article</div>
                          )}
                        </div>
                        <div>
                          <h2 className="t-h2" style={{ marginBottom: 16 }}>{featured.title}</h2>
                          {featured.tag && (
                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', marginBottom: 24 }}>
                              {featured.tag.split(',').map((t, i) => (
                                <span key={i} style={{ fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: '400', letterSpacing: '0.08em', color: 'var(--taupe)' }}>#{t.trim()}</span>
                              ))}
                            </div>
                          )}
                          <p className="t-body-lg" style={{ marginBottom: 32 }}>{truncate(featured.body, 220)}</p>
                          <span style={{ fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 500, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--gold)' }}>Read Article →</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </section>
              )}

              {restPosts.length > 0 && (
                <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:0 }} className="blog-grid-sm">
                  {restPosts.map(post => (
                    <div key={post.id} onClick={() => navigate('post/' + post.id)} onMouseEnter={() => setHovered(post.id)} onMouseLeave={() => setHovered(null)} style={{ background:hovered===post.id?'var(--ink)':'var(--paper)', padding:'clamp(24px,3vw,36px)', transition:'background 0.35s cubic-bezier(0.16,1,0.3,1)', cursor:'pointer', display:'flex', flexDirection:'column', gap:'12px', borderRight:'2px solid var(--fog)', borderBottom:'2px solid var(--fog)' }}>
                      <h3 style={{ fontFamily:'var(--serif)', fontSize:'clamp(18px,2vw,24px)', fontWeight:'400', color:hovered===post.id?'var(--paper)':'var(--ink)', lineHeight:1.3, transition:'color 0.3s', marginBottom: 10 }}>{post.title}</h3>
                      {post.tag && (
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                          {post.tag.split(',').map((t, i) => (
                            <span key={i} style={{ fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: '400', letterSpacing: '0.06em', color: hovered===post.id ? 'rgba(248,245,239,0.5)' : 'var(--taupe)', transition: 'color 0.3s' }}>#{t.trim()}</span>
                          ))}
                        </div>
                      )}
                      <p className="t-body" style={{ fontSize:'14px', color:hovered===post.id?'rgba(248,245,239,0.55)':'var(--taupe)', transition:'color 0.3s', flex:1 }}>{truncate(post.body)}</p>
                      <span onClick={() => navigate('post/' + post.id)} style={{ fontFamily:'var(--sans)', fontSize:'11px', fontWeight:'500', letterSpacing:'0.1em', textTransform:'uppercase', color:gold, display:'flex', alignItems:'center', gap:'6px', width:'fit-content', marginTop:'8px' }}>
                        Read <svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="2" y1="7" x2="12" y2="7"/><polyline points="8,3 12,7 8,11"/></svg>
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      </section>

      <CTABand navigate={navigate} accentColor={gold} heading="Ready to put these ideas to work?" sub="Book a strategy call and let's apply these insights directly to your business." />
      <style>{`
        @media(max-width:760px){ .blog-grid-sm{grid-template-columns:1fr!important;} }
        @media(min-width:761px) and (max-width:960px){ .blog-grid-sm{grid-template-columns:repeat(2,1fr)!important;} }
      `}</style>
    </div>
  );
}

// ── CONTACT PAGE ──────────────────────────────────────
function ContactPage({ tweaks }) {
  const gold = tweaks.accentColor;
  const [form, setForm] = React.useState({ name:'', email:'', phone:'', message:'', sms:false });
  const [submitted, setSubmitted] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  useReveal();

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Name is required';
    if (!form.email.trim() || !/\S+@\S+\.\S+/.test(form.email)) e.email = 'Valid email is required';
    if (!form.message.trim()) e.message = 'Message is required';
    if (!form.sms) e.sms = 'Please agree to receive SMS messages to submit this form';
    return e;
  };

  const handleSubmit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setSubmitting(true);
    try {
      const res = await fetch(`${API_BASE}/api/contact`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone,
          message: form.message,
          sms_consent: form.sms ? 1 : 0,
        }),
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        setErrors({ message: 'Something went wrong. Please try again.' });
      }
    } catch {
      setErrors({ message: 'Network error. Please try again.' });
    } finally {
      setSubmitting(false);
    }
  };

  const inp = (id, label, type='text', placeholder='') => (
    <div style={{ display:'flex', flexDirection:'column', gap:'8px' }}>
      <label htmlFor={id} style={{ fontFamily:'var(--sans)', fontSize:'11px', fontWeight:'500', letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--taupe)' }}>{label}</label>
      <input id={id} type={type} placeholder={placeholder} value={form[id]} onChange={e => { setForm(f => ({...f, [id]:e.target.value})); setErrors(er => ({...er, [id]:''})); }}
        style={{ padding:'14px 16px', background:'var(--paper)', border:`1px solid ${errors[id]?'#C0392B':'var(--fog)'}`, fontFamily:'var(--sans)', fontSize:'15px', fontWeight:'300', color:'var(--ink)', outline:'none', transition:'border-color 0.2s', width:'100%' }}
        onFocus={e=>e.target.style.borderColor=gold} onBlur={e=>e.target.style.borderColor=errors[id]?'#C0392B':'var(--fog)'} />
      {errors[id] && <span style={{ fontFamily:'var(--sans)', fontSize:'12px', color:'#C0392B' }}>{errors[id]}</span>}
    </div>
  );

  return (
    <div>
      <PageHero
        eyebrow="Let's Talk"
        title="Connect With Us"
        subhead="That conversation doesn't cost anything, and it just might change everything."
        imgUrl="assets/images/contact/banner.png"
        accentColor={gold}
      />

      <section style={{ background:'var(--paper)', padding:'clamp(64px,8vw,100px) 0' }}>
        <div style={{ maxWidth:'1280px', margin:'0 auto', padding:'0 clamp(24px,5vw,80px)' }}>
          <div style={{ display:'grid', gridTemplateColumns:'5fr 7fr', gap:'clamp(40px,6vw,96px)', alignItems:'start' }} className="two-col">

            {/* Left: contact info */}
            <div className="reveal">
              <p className="t-eyebrow" style={{ color:gold, marginBottom:'18px' }}>Reach Out</p>
              <h2 className="t-h2" style={{ marginBottom:'20px' }}>We'd Love to Hear From You</h2>
              <div style={{ width:'44px', height:'1px', background:gold, marginBottom:'36px' }} />

              <div style={{ display:'flex', flexDirection:'column', gap:'28px', marginBottom:'48px' }}>
                {[
                  { label:'Phone', val:'(918) 201-0820', href:'tel:9182010820', icon:<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.3" width="18" height="18"><path d="M3 5a2 2 0 012-2h2l2 4-2 2a11 11 0 005 5l2-2 4 2v2a2 2 0 01-2 2C8 18 2 12 2 5a2 2 0 011-1.73L3 5z"/></svg> },
                  { label:'Email', val:'hello@meteracollective.com', href:'mailto:hello@meteracollective.com', icon:<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.3" width="18" height="18"><rect x="2" y="5" width="16" height="12" rx="1"/><path d="M2 5l8 7 8-7"/></svg> },
                  { label:'Location', val:'Tuskahoma, Oklahoma', href:null, icon:<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.3" width="18" height="18"><path d="M10 2a6 6 0 016 6c0 5-6 10-6 10S4 13 4 8a6 6 0 016-6z"/><circle cx="10" cy="8" r="2"/></svg> },
                ].map(c => (
                  <div key={c.label} style={{ display:'flex', gap:'16px', alignItems:'flex-start' }}>
                    <div style={{ width:'36px', height:'36px', background:'var(--fog)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, color:gold }}>{c.icon}</div>
                    <div>
                      <p style={{ fontFamily:'var(--sans)', fontSize:'10px', fontWeight:'500', letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--taupe)', marginBottom:'5px' }}>{c.label}</p>
                      {c.href
                        ? <a href={c.href} style={{ fontFamily:'var(--sans)', fontSize:'15px', fontWeight:'400', color:'var(--ink)', textDecoration:'none' }}>{c.val}</a>
                        : <p style={{ fontFamily:'var(--sans)', fontSize:'15px', fontWeight:'400', color:'var(--ink)' }}>{c.val}</p>
                      }
                    </div>
                  </div>
                ))}
              </div>

              <div style={{ display:'flex', gap:'14px', marginBottom:'48px' }}>
                {[
                  { label:'Instagram', href:'https://www.instagram.com/meteracollective/', icon:<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.5" fill="currentColor"/></svg> },
                  { label:'Facebook', href:'https://www.facebook.com/meteracollective', icon:<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z"/></svg> },
                  { label:'LinkedIn', href:'https://www.linkedin.com/company/metera-collective/', icon:<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M16 8a6 6 0 016 6v7h-4v-7a2 2 0 00-2-2 2 2 0 00-2 2v7h-4v-7a6 6 0 016-6z"/><rect x="2" y="9" width="4" height="12"/><circle cx="4" cy="4" r="2"/></svg> },
                ].map(s => (
                  <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.label}
                    style={{ color:'var(--taupe)', transition:'color 0.2s', display:'flex', alignItems:'center', justifyContent:'center', width:'40px', height:'40px', border:'1px solid var(--fog)', flexShrink:0 }}
                    onMouseEnter={e => e.currentTarget.style.color = gold}
                    onMouseLeave={e => e.currentTarget.style.color = 'var(--taupe)'}
                  >{s.icon}</a>
                ))}
              </div>

              <blockquote style={{ fontFamily:'var(--serif)', fontStyle:'italic', fontSize:'clamp(17px,1.8vw,22px)', fontWeight:'300', lineHeight:1.5, paddingLeft:'20px', borderLeft:`2px solid ${gold}`, color:'var(--ink)' }}>
                "Helping businesses grow is not just what I do — it's what I was made for."
                <footer style={{ fontFamily:'var(--sans)', fontSize:'12px', fontStyle:'normal', fontWeight:'500', letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--taupe)', marginTop:'12px' }}>— Brenda Richey</footer>
              </blockquote>
            </div>

            {/* Right: form */}
            <div className="reveal reveal-delay-1">
              {submitted ? (
                <div style={{ padding:'clamp(40px,5vw,64px)', background:'var(--paper-warm)', border:`1px solid ${gold}`, textAlign:'center' }}>
                  <div style={{ width:'48px', height:'48px', borderRadius:'50%', background:gold, display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 24px' }}>
                    <svg viewBox="0 0 20 20" fill="none" stroke="var(--paper)" strokeWidth="2" width="22" height="22"><polyline points="4,10 8,14 16,6"/></svg>
                  </div>
                  <h3 className="t-h3" style={{ marginBottom:'16px' }}>Message Received</h3>
                  <p className="t-body">Thank you for reaching out. We'll be in touch within one business day.</p>
                </div>
              ) : (
                <form onSubmit={handleSubmit} noValidate style={{ display:'flex', flexDirection:'column', gap:'20px' }}>
                  <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'20px' }} className="form-grid">
                    {inp('name', 'Full Name', 'text', 'Jane Smith')}
                    {inp('email', 'Email Address', 'email', 'jane@company.com')}
                  </div>
                  {inp('phone', 'Phone Number (optional)', 'tel', '(555) 000-0000')}
                  <div style={{ display:'flex', flexDirection:'column', gap:'8px' }}>
                    <label htmlFor="message" style={{ fontFamily:'var(--sans)', fontSize:'11px', fontWeight:'500', letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--taupe)' }}>Your Message</label>
                    <textarea id="message" rows="5" maxLength={1000} placeholder="Tell us about your business and what you're looking to achieve..." value={form.message} onChange={e => { setForm(f=>({...f,message:e.target.value})); setErrors(er=>({...er,message:''})); }}
                      style={{ padding:'14px 16px', background:'var(--paper)', border:`1px solid ${errors.message?'#C0392B':'var(--fog)'}`, fontFamily:'var(--sans)', fontSize:'15px', fontWeight:'300', color:'var(--ink)', outline:'none', resize:'vertical', transition:'border-color 0.2s' }}
                      onFocus={e=>e.target.style.borderColor=gold} onBlur={e=>e.target.style.borderColor=errors.message?'#C0392B':'var(--fog)'} />
                    {errors.message && <span style={{ fontFamily:'var(--sans)', fontSize:'12px', color:'#C0392B' }}>{errors.message}</span>}
                    <span style={{ fontFamily:'var(--sans)', fontSize:'11px', color:'var(--taupe)', textAlign:'right', display:'block', marginTop:'4px' }}>{form.message.length}/1000</span>
                  </div>
                  <div>
                    <label style={{ display:'flex', alignItems:'flex-start', gap:'12px', cursor:'pointer' }}>
                      <input type="checkbox" checked={form.sms} onChange={e=>{ setForm(f=>({...f,sms:e.target.checked})); setErrors(er=>({...er,sms:''})); }} style={{ marginTop:'3px', accentColor:gold, width:'16px', height:'16px' }} />
                      <span style={{ fontFamily:'var(--sans)', fontSize:'13px', fontWeight:'300', color:'var(--taupe)', lineHeight:'1.5' }}>By checking this box, you agree to receive SMS messages from Metera related to appointment scheduling. Msg &amp; data rates may apply.</span>
                    </label>
                    {errors.sms && <span style={{ fontFamily:'var(--sans)', fontSize:'12px', color:'#C0392B', marginTop:'6px', display:'block' }}>{errors.sms}</span>}
                  </div>
                  <button type="submit" disabled={submitting} style={{ padding:'16px 32px', background:gold, color:'var(--paper)', fontFamily:'var(--sans)', fontSize:'12px', fontWeight:'500', letterSpacing:'0.14em', textTransform:'uppercase', border:'none', cursor:'pointer', transition:'background 0.25s', width:'fit-content', display:'flex', alignItems:'center', gap:'10px', opacity: submitting ? 0.6 : 1 }}
                    onMouseEnter={e=>e.target.style.background='#8C6E1C'} onMouseLeave={e=>e.target.style.background=gold}>
                    {submitting ? 'Sending…' : 'Send Message'}
                    <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="2" y1="7" x2="12" y2="7"/><polyline points="8,3 12,7 8,11"/></svg>
                  </button>
                  <p style={{ fontFamily:'var(--sans)', fontSize:'11px', fontWeight:'300', color:'var(--taupe)', lineHeight:'1.6' }}>No mobile information will be shared with third parties for marketing purposes.</p>
                </form>
              )}
            </div>
          </div>
        </div>
      </section>
      <style>{`
        @media(max-width:720px){.two-col{grid-template-columns:1fr!important;}}
        @media(max-width:480px){.form-grid{grid-template-columns:1fr!important;}}
      `}</style>
    </div>
  );
}

// ── POST PAGE ─────────────────────────────────────────
const PostPage = ({ postId, navigate, tweaks }) => {
  const gold = tweaks.accentColor;
  const [post, setPost] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [notFound, setNotFound] = React.useState(false);
  const [prevPost, setPrevPost] = React.useState(null);
  const [nextPost, setNextPost] = React.useState(null);

  React.useEffect(() => {
    if (!postId) { setNotFound(true); setLoading(false); return; }
    setPrevPost(null);
    setNextPost(null);
    Promise.all([
      fetch(`${API_BASE}/api/posts/${postId}`).then(r => { if (!r.ok) throw new Error(); return r.json(); }),
      fetch(`${API_BASE}/api/posts`).then(r => r.json()),
    ])
      .then(([current, all]) => {
        setPost(current);
        if (Array.isArray(all)) {
          const idx = all.findIndex(p => String(p.id) === String(postId));
          // API returns posts sorted by created_at DESC, so:
          // next (newer) = idx - 1, prev (older) = idx + 1
          setNextPost(idx > 0 ? all[idx - 1] : null);
          setPrevPost(idx < all.length - 1 ? all[idx + 1] : null);
        }
        setLoading(false);
      })
      .catch(() => { setNotFound(true); setLoading(false); });
  }, [postId]);

  if (loading) return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--sans)', color: 'var(--taupe)' }}>
      Loading…
    </div>
  );

  if (notFound || !post) return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '24px' }}>
      <p style={{ fontFamily: 'var(--serif)', fontSize: '28px', color: 'var(--ink)' }}>Post not found.</p>
      <button onClick={() => navigate('blogs')} className="btn-ghost">← Back to Blog</button>
    </div>
  );

  const paragraphs = (post.body || '').split('\n\n').filter(p => p.trim());
  const dateStr = post.created_at ? new Date(post.created_at).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) : '';

  return (
    <div>
      {/* Hero */}
      <section style={{ minHeight: '100vh', background: 'var(--ink)', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: 'clamp(40px,6vw,80px)', position: 'relative', overflow: 'hidden' }}>
        {post.image_url && (
          <img
            src={post.image_url}
            alt={post.title}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center', opacity: 0.7 }}
          />
        )}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(12,12,12,0.92) 0%, rgba(12,12,12,0.25) 50%, rgba(12,12,12,0.15) 100%)' }} />
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: '3px', background: `linear-gradient(to bottom, transparent, ${gold}, transparent)`, opacity: 0.6 }} />
        <div style={{ maxWidth: '900px', position: 'relative', zIndex: 1 }}>
          {post.tag && (
            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', marginBottom: '24px' }}>
              {post.tag.split(',').map((t, i) => (
                <span key={i} style={{ padding: '5px 14px', border: `1px solid ${gold}`, color: gold, fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: '500', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
                  {t.trim()}
                </span>
              ))}
            </div>
          )}
          <h1 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(32px,5vw,64px)', fontWeight: '300', color: 'var(--paper)', lineHeight: 1.15, marginBottom: '20px' }}>
            {post.title}
          </h1>
          <p style={{ fontFamily: 'var(--sans)', fontSize: '13px', color: 'rgba(248,245,239,0.45)', letterSpacing: '0.08em' }}>{dateStr}</p>
        </div>
      </section>

      {/* Body */}
      <section style={{ background: 'var(--paper)', padding: 'clamp(64px,8vw,100px) 0' }}>
        <div style={{ maxWidth: '720px', margin: '0 auto', padding: '0 clamp(24px,5vw,48px)' }}>
          <button onClick={() => navigate('blogs')} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--sans)', fontSize: '12px', fontWeight: '500', letterSpacing: '0.1em', textTransform: 'uppercase', color: gold, display: 'flex', alignItems: 'center', gap: '8px', padding: 0, marginBottom: '48px' }}>
            <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="12" y1="7" x2="2" y2="7"/><polyline points="6,3 2,7 6,11"/></svg>
            Back to Blog
          </button>
          {paragraphs.map((para, i) => (
            <p key={i} style={{ fontFamily: 'var(--sans)', fontSize: 'clamp(15px,1.6vw,17px)', fontWeight: '300', color: 'var(--ink)', lineHeight: '1.85', marginBottom: '28px' }}>
              {para}
            </p>
          ))}
        </div>
      </section>

      {/* Prev / Next navigation */}
      {(prevPost || nextPost) && (
        <section style={{ background: 'var(--paper-warm)', borderTop: '1px solid var(--fog)' }}>
          <div style={{ maxWidth: '720px', margin: '0 auto', padding: '0 clamp(24px,5vw,48px)', display: 'grid', gridTemplateColumns: prevPost && nextPost ? '1fr 1fr' : '1fr', gap: 0 }}>
            {prevPost && (
              <button
                onClick={() => navigate('post/' + prevPost.id)}
                style={{ background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', padding: 'clamp(28px,4vw,48px) 0', borderRight: nextPost ? '1px solid var(--fog)' : 'none', paddingRight: nextPost ? 'clamp(20px,3vw,40px)' : 0 }}
              >
                <p style={{ fontFamily: 'var(--sans)', fontSize: '10px', fontWeight: '500', letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '6px' }}>
                  <svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="12" y1="7" x2="2" y2="7"/><polyline points="6,3 2,7 6,11"/></svg>
                  Previous
                </p>
                <p style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(16px,1.8vw,20px)', fontWeight: '400', color: 'var(--ink)', lineHeight: 1.3 }}>{prevPost.title}</p>
              </button>
            )}
            {nextPost && (
              <button
                onClick={() => navigate('post/' + nextPost.id)}
                style={{ background: 'none', border: 'none', cursor: 'pointer', textAlign: 'right', padding: 'clamp(28px,4vw,48px) 0', paddingLeft: prevPost ? 'clamp(20px,3vw,40px)' : 0, marginLeft: prevPost ? 'auto' : 'auto', width: '100%' }}
              >
                <p style={{ fontFamily: 'var(--sans)', fontSize: '10px', fontWeight: '500', letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: '10px', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '6px' }}>
                  Next
                  <svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="2" y1="7" x2="12" y2="7"/><polyline points="8,3 12,7 8,11"/></svg>
                </p>
                <p style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(16px,1.8vw,20px)', fontWeight: '400', color: 'var(--ink)', lineHeight: 1.3 }}>{nextPost.title}</p>
              </button>
            )}
          </div>
        </section>
      )}

      <CTABand navigate={navigate} accentColor={gold} />
    </div>
  );
};

Object.assign(window, { MethodPage, FAQsPage, BlogsPage, ContactPage, PostPage });
