import { LitElement, css, html } from 'lit';
import { property, customElement } from 'lit/decorators.js';
import { Relay } from 'nostr-tools';

import '@shoelace-style/shoelace/dist/components/card/card.js';
import '@shoelace-style/shoelace/dist/components/button/button.js';

import { styles } from '../styles/shared-styles';




@customElement('note-wall')
export class NoteWall extends LitElement {

@property({ type: Array }) notes: { content: string; date: string }[] = [];
@property({ type: String }) relayName: string = '';


note = ''; // store notes

  static styles = [
    styles,
    css`

.comment-wall .main-section-header {
  margin-bottom: 3px;
}

.comment-wall .main-section-h2 {
  margin-bottom: 0;
}

#comment-counter {
  margin-top: 0;
  margin-left: 15px;
  margin-bottom: 3px;
}

.comment-wall table {
  margin: auto;
  margin-bottom: 5px;
  color: black;
}


.comment-wall th {
  width: 158px;
  padding: 3px;
  vertical-align: top;
}

.comment-wall td {
  vertical-align: top;
  width: 269px;
  padding: 3px;
}

.comment-wall figcaption,
.comment-wall figure {
  margin: 0;
}

.comment-wall figcaption {
  margin-bottom: 1em;
}

.comment-wall figure {
  margin-bottom: 49.33px;
}

.comment-wall h3 {
  font-size: 10pt;
  margin: 0;
  margin-bottom: 3em;
}

.comment-wall p {
  font-weight: normal;
  text-align: center;
  margin: 0;
}

#add-comment {
  text-align: right;
  margin-right: 10px;
  margin-bottom: 5px;
}


  `];



  getUserLang() {

    return navigator.language || 'en';

  }

  async firstUpdated() {
    // this method is a lifecycle even in lit
    // for more info check out the lit docs https://lit.dev/docs/components/lifecycle/
    console.log('Here are some recent notes from the neighborhood');
  }

  async connectedCallback(): Promise<void> {
    super.connectedCallback();
  await Promise.all([
    this.fetchNotes(),

  ]);

}


/* async translateText(text: string, targetLang: string) {
  try {
    const response = await axios.post('https://api-free.deepl.com/v2/translate', {
      text, target_lang: targetLang });

    return response.data.translations[0].text;  // Assuming DeepL's API structure
  } catch (error: any) {
    console.error('Error during translation:', error.response?.data || error.message);
    return '';
  }
} */




async fetchNotes() {
 // const ifcaRelay = await Relay.connect('wss://hi.myvoiceourstory.org');

  const migsRelay = await Relay.connect('wss://notes.miguelalmodo.com');
  console.log(`connected to ${migsRelay.url}`);


// store the relay name
  this.relayName = migsRelay.url;


  const sub = migsRelay.subscribe([
    {
      kinds: [30023], // short and long form notes
      limit: 5,
    }
  ], {
    onevent: async (event) => {
      console.log('Event received:', event);
      this.notes = [...this.notes, {
        content: event.content,
        date: new Date(event.created_at * 1000).toLocaleDateString(),
      }];
      this.requestUpdate();
      console.log(migsRelay)

    },
    oneose: () => {
      sub.close();
      this.requestUpdate();
    },
  });

}

async displayLongNotes() {

}




  share() {
    if ((navigator as any).share) {
      (navigator as any).share({
        title: 'Nostr Micro Client',
        text: 'Share this with your homie!',
        url: 'https://miguelalmodo.com/',
      });
    }
  }

  render() {
    return html`
      <app-header ?enableBack="${true}"></app-header>
      <main> <div id="welcomeBar">
<sl-card id="WelcomeCard">
    <section>

    <header class="main-section-header">
            <h2 class="main-section-h2">Recent Notes from ${this.relayName}</h2>
    </header>




   <table class="comment-wall">
  ${this.notes.map(note => {
    // extract URL from note content
    const urlMatch = note.content.match(/https?:\/\/[^\s]+/);
    const textContent = note.content.replace(urlMatch?.[0] || '', '').trim();


    // Check for yt links and extract video ID
    const youtubeRegex = /(?:https?:\/\/(?:www\.)?youtube\.com\/watch\?v=|https?:\/\/youtu\.be\/)([a-zA-Z0-9_-]{11})/;
    const youtubeMatch = urlMatch?.[0].match(youtubeRegex);
    const youtubeVideoId = youtubeMatch ? youtubeMatch[1] : null;

    // build yt thumbnail URL if applicable
    const thumbnailUrl = youtubeVideoId
      ? `https://img.youtube.com/vi/${youtubeVideoId}/maxresdefault.jpg`
      : null;

      //check for image links
    const imgRegex = /(https?:\/\/[^\s]+\.(?:jpg|jpeg|png|gif))/i;
    const imgMatch = urlMatch?.find(url => imgRegex.test(url));

    return html`
      <tr>
        <td><h3>${note.date}</h3></td>
        <td>
          <p>${textContent}</p>
          ${thumbnailUrl
            ? html`<img src="${thumbnailUrl}" alt="YouTube thumbnail" style="max-width: 30%; height: 30%;">`
            : imgMatch
              ? html`<img src="${imgMatch}" alt="Note image" style="max-width: 30%; height: 30%;">`
              : ''}
        </td>
      </tr>
    `;
  })}
</table>



    </section></main>
</sl-card>
    `;
  }
}
